2025-09-29_byte-multiplication-trick.html


001| #:name::Byte Multiplication Trick
002| #:link::https://thehardcorecoder.com/2025/09/29/byte-multiplication-trick/
003| #:date::2025-09-29
004| #:code::
005| def multiply_bs_0 (bs1:bytes, bs2:bytes) -> bytes:
006|     '''Multiply byte strings. Version 0. (No MulTable)'''
007|     print(f'multiply0({bs1.hex(".")}, {bs2.hex(".")})')
008| 
009|     # Output buffer
010|     buf = [0] * (len(bs1) + len(bs2))
011| 
012|     # Generate Cartesian products...
013|     for ix1,b1 in enumerate(bs1):
014|         for ix2,b2 in enumerate(bs2):
015|             # Buffer index...
016|             ix = ix1+ix2
017| 
018|             # Determine product and any carry...
019|             carry,product = divmod(b1*b2, 256)
020|             print(f'[{ix}]: {b1} * {b2} = {product}, {carry}')
021| 
022|             # Add to result buffer...
023|             buf[ix] += product
024|             buf[ix+1] += carry
025| 
026|     # Ripply carry buffer...
027|     for ix in range(len(buf)):
028|         carry,value = divmod(buf[ix], 256)
029|         # Handle overflow...
030|         if carry:
031|             buf[ix] = value
032|             buf[ix+1] += carry
033| 
034|     print(f'multiply0.exit: {buf}')
035|     return bytes(buf)
036| 
037| 
038| if __name__ == '__main__':
039|     print()
040| 
041|     bs1 = bytes([255,255])
042|     bs2 = bytes([255])
043|     v1 = int.from_bytes(bs1, byteorder='little')
044|     v2 = int.from_bytes(bs2, byteorder='little')
045| 
046|     res = multiply_bs_0(bs1, bs2)
047|     val = int.from_bytes(res, byteorder='little')
048|     flg = 'Ok!' if (v1*v2)==val else str(v1*v2)
049|     print()
050| 
051|     print(f'{list(bs1)} × {list(bs2)} = {res}')
052|     print(f'{v1} × {v2} = {val} ({flg})')
053|     print()
054| 
055| #:code::
056| itobs = lambda n: bytes(reversed(divmod(n,256)))
057| 
058| MulTable = [[itobs(a*b) for b in range(256)] for a in range(256)]
059| 
060| #:code::
061| from examples import MulTable
062| 
063| if __name__ == '__main__':
064|     print()
065| 
066|     #Show off some byte multiplications...
067|     print(f'{MulTable[0x00][0x00] = }')
068|     print(f'{MulTable[0x01][0x01] = }')
069|     print(f'{MulTable[0x02][0x02] = }')
070|     print(f'{MulTable[0x2a][0x2a] = }')
071|     print(f'{MulTable[0x45][0x67] = }')
072|     print(f'{MulTable[0x80][0x80] = }')
073|     print(f'{MulTable[0xAB][0xCD] = }')
074|     print(f'{MulTable[0xff][0xff] = }')
075|     print(f'')
076| 
077| #:code::
078| from examples import MulTable
079| 
080| def multiply_bs_1 (bs1:bytes, bs2:bytes) -> bytes:
081|     '''Multiply byte strings. Version 1.'''
082|     print(f'multiply1({bs1.hex(".")}, {bs2.hex(".")})')
083| 
084|     # Output buffer...
085|     buf = [0] * (len(bs1) + len(bs2))
086| 
087|     # Generate Cartesian products...
088|     for ix1,b1 in enumerate(bs1):
089|         for ix2,b2 in enumerate(bs2):
090|             # Buffer index...
091|             ix = ix1+ix2
092| 
093|             # Get b1*b2 product...
094|             res = MulTable[b1][b2]
095|             print(f'[{ix}]: {b1} * {b2} = {res}')
096| 
097|             # Add LSB...
098|             buf[ix] += res[0]
099|             # Add MSB...
100|             buf[ix+1] += res[1]
101| 
102|     # Ripply carry buffer...
103|     for ix in range(len(buf)):
104|         carry,value = divmod(buf[ix], 256)
105|         # Handle overflow...
106|         if carry:
107|             buf[ix] = value
108|             buf[ix+1] += carry
109| 
110|     # Return buffer...
111|     print(f'multiply1.exit: {buf}')
112|     return bytes(buf)
113| 
114| 
115| if __name__ == '__main__':
116|     print()
117| 
118|     bs1 = bytes([255,255])
119|     bs2 = bytes([255])
120|     v1 = int.from_bytes(bs1, byteorder='little')
121|     v2 = int.from_bytes(bs2, byteorder='little')
122| 
123|     res = multiply_bs_1(bs1, bs2)
124|     val = int.from_bytes(res, byteorder='little')
125|     flg = 'Ok!' if (v1*v2)==val else str(v1*v2)
126|     print()
127| 
128|     print(f'{list(bs1)} × {list(bs2)} = {res}')
129|     print(f'{v1} × {v2} = {val} ({flg})')
130|     print()
131| 
132| #:code::
133| from examples import MulTable
134| 
135| def multiply_bs_2 (bs1:bytes, bs2:bytes) -> bytes:
136|     '''Multiply byte strings. Version 2.'''
137|     print(f'multiply2({bs1.hex(".")}, {bs2.hex(".")})')
138| 
139|     # Accumulator...
140|     terms = {ix:0 for ix in range(len(bs1) + len(bs2))}
141| 
142|     # Generate Cartesian products...
143|     for ix1,b1 in enumerate(bs1):
144|         for ix2,b2 in enumerate(bs2):
145|             # Buffer index...
146|             ix = ix1+ix2
147| 
148|             # Get product and add to terms...
149|             res = MulTable[b1][b2]
150|             terms [ix] += res[0]
151|             terms [ix+1] += res[1]
152| 
153|             answer = [terms[ix] for ix in sorted(terms.keys())]
154|             print(f'multiply2.products[{b1},{b2}]: {answer}')
155| 
156|     # Ripple carry the terms...
157|     for ix in sorted(terms.keys()):
158|         carry,value = divmod(terms[ix], 256)
159|         if 0 < carry:
160|             terms[ix] = value
161|             terms[ix+1] += carry
162| 
163|     # Return the terms...
164|     answer = [terms[ix] for ix in sorted(terms.keys())]
165|     print(f'multiply2.exit: {answer}')
166|     return bytes(answer)
167| 
168| 
169| if __name__ == '__main__':
170|     print()
171| 
172|     bs1 = bytes([255,255])
173|     bs2 = bytes([255])
174|     v1 = int.from_bytes(bs1, byteorder='little')
175|     v2 = int.from_bytes(bs2, byteorder='little')
176| 
177|     res = multiply_bs_2(bs1, bs2)
178|     val = int.from_bytes(res, byteorder='little')
179|     flg = 'Ok!' if (v1*v2)==val else str(v1*v2)
180|     print()
181| 
182|     print(f'{list(bs1)} × {list(bs2)} = {res}')
183|     print(f'{v1} × {v2} = {val} ({flg})')
184|     print()
185| 
186| #:code::
187| from examples import MulTable
188| 
189| def multiply_bs_3 (bs1:bytes, bs2:bytes) -> bytes:
190|     '''Multiply byte strings. Version 2.'''
191|     print(f'multiply3({bs1.hex(".")}, {bs2.hex(".")})')
192| 
193|     # Output buffer...
194|     buf = [0] * (len(bs1) + len(bs2))
195| 
196|     # Accumulator...
197|     terms = {}
198| 
199|     # Generate Cartesian products...
200|     for ix1,b1 in enumerate(bs1):
201|         for ix2,b2 in enumerate(bs2):
202|             # Terms index...
203|             key = (ix1,ix2)
204| 
205|             # Add to terms...
206|             terms[key] = MulTable[b1][b2]
207|             print(f'multiply3.product[{b1},{b2}]: {terms[key]}')
208| 
209|     # Sum the terms into the result buffer...
210|     for key in sorted(terms.keys()):
211|         ix = sum(key)
212|         res = terms[key]
213|         buf[ix] += res[0]
214|         buf[ix+1] += res[1]
215| 
216|     # Ripply carry buffer...
217|     for ix in range(len(buf)):
218|         carry,value = divmod(buf[ix], 256)
219|         # Handle overflow...
220|         if carry:
221|             buf[ix] = value
222|             buf[ix+1] += carry
223| 
224|     # Return buffer...
225|     print(f'multiply3.exit: {buf}')
226|     return bytes(buf)
227| 
228| 
229| if __name__ == '__main__':
230|     print()
231| 
232|     bs1 = bytes([255,255])
233|     bs2 = bytes([255])
234|     v1 = int.from_bytes(bs1, byteorder='little')
235|     v2 = int.from_bytes(bs2, byteorder='little')
236| 
237|     res = multiply_bs_3(bs1, bs2)
238|     val = int.from_bytes(res, byteorder='little')
239|     flg = 'Ok!' if (v1*v2)==val else str(v1*v2)
240|     print()
241| 
242|     print(f'{list(bs1)} × {list(bs2)} = {res}')
243|     print(f'{v1} × {v2} = {val} ({flg})')
244|     print()
245| 
246| #:code::
247| from sys import argv
248| from time import perf_counter_ns
249| import examples as eg
250| 
251| if __name__ == '__main__':
252|     times = int(argv[2]) if 2 < len(argv) else 1000
253| 
254|     # Operand strings...
255|     s1 = argv[2] if 2 < len(argv) else '255,255,255,255,255,255,255,255,255,255,255,255'
256|     s2 = argv[3] if 3 < len(argv) else '255,255,255,255,255,255,255,255,255,255,255,255'
257| 
258|     # Convert string to integer values...
259|     ds1 = [int(d, base=0) for d in s1.split(',')]
260|     ds2 = [int(d, base=0) for d in s2.split(',')]
261| 
262|     # Make the byte strings for multiplying...
263|     bs1 = bytes(ds1)
264|     bs2 = bytes(ds2)
265|     v1 = int.from_bytes(bs1, byteorder='little')
266|     v2 = int.from_bytes(bs2, byteorder='little')
267|     answer = v1 * v2
268|     print(f'1 = {v1:,}')
269|     print(f'2 = {v2:,}')
270|     print(f'A = {answer:,}')
271|     print()
272| 
273|     # Version 1...
274|     t0 = perf_counter_ns()
275|     for _ in range(times):
276|         res = eg.multiply_bs_0(bs1, bs2)
277|     t1 = perf_counter_ns()
278|     val = int.from_bytes(res, byteorder='little')
279|     print(f'version 0: {(t1-t0)/1000000:.3f} ms')
280|     print('Ok!' if val==answer else f'OOPS: {val:,}')
281| 
282|     # Version 1...
283|     t0 = perf_counter_ns()
284|     for _ in range(times):
285|         res = eg.multiply_bs_1(bs1, bs2)
286|     t1 = perf_counter_ns()
287|     val = int.from_bytes(res, byteorder='little')
288|     print(f'version 1: {(t1-t0)/1000000:.3f} ms')
289|     print('Ok!' if val==answer else f'OOPS: {val:,}')
290| 
291|     # Version 2...
292|     t0 = perf_counter_ns()
293|     for _ in range(times):
294|         res = eg.multiply_bs_2(bs1, bs2)
295|     t1 = perf_counter_ns()
296|     val = int.from_bytes(res, byteorder='little')
297|     print(f'version 2: {(t1-t0)/1000000:.3f} ms')
298|     print('Ok!' if val==answer else f'OOPS: {val:,}')
299| 
300|     # Version 3...
301|     t0 = perf_counter_ns()
302|     for _ in range(times):
303|         res = eg.multiply_bs_3(bs1, bs2)
304|     t1 = perf_counter_ns()
305|     val = int.from_bytes(res, byteorder='little')
306|     print(f'version 3: {(t1-t0)/1000000:.3f} ms')
307|     print('Ok!' if val==answer else f'OOPS: {val:,}')
308| 
309| #:end:code::
310|