2025-09-29_byte-multiplication-trick.html
001|
002|
003|
004|
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|
010| buf = [0] * (len(bs1) + len(bs2))
011|
012|
013| for ix1,b1 in enumerate(bs1):
014| for ix2,b2 in enumerate(bs2):
015|
016| ix = ix1+ix2
017|
018|
019| carry,product = divmod(b1*b2, 256)
020| print(f'[{ix}]: {b1} * {b2} = {product}, {carry}')
021|
022|
023| buf[ix] += product
024| buf[ix+1] += carry
025|
026|
027| for ix in range(len(buf)):
028| carry,value = divmod(buf[ix], 256)
029|
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|
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|
061| from examples import MulTable
062|
063| if __name__ == '__main__':
064| print()
065|
066|
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|
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|
085| buf = [0] * (len(bs1) + len(bs2))
086|
087|
088| for ix1,b1 in enumerate(bs1):
089| for ix2,b2 in enumerate(bs2):
090|
091| ix = ix1+ix2
092|
093|
094| res = MulTable[b1][b2]
095| print(f'[{ix}]: {b1} * {b2} = {res}')
096|
097|
098| buf[ix] += res[0]
099|
100| buf[ix+1] += res[1]
101|
102|
103| for ix in range(len(buf)):
104| carry,value = divmod(buf[ix], 256)
105|
106| if carry:
107| buf[ix] = value
108| buf[ix+1] += carry
109|
110|
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|
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|
140| terms = {ix:0 for ix in range(len(bs1) + len(bs2))}
141|
142|
143| for ix1,b1 in enumerate(bs1):
144| for ix2,b2 in enumerate(bs2):
145|
146| ix = ix1+ix2
147|
148|
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|
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|
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|
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|
194| buf = [0] * (len(bs1) + len(bs2))
195|
196|
197| terms = {}
198|
199|
200| for ix1,b1 in enumerate(bs1):
201| for ix2,b2 in enumerate(bs2):
202|
203| key = (ix1,ix2)
204|
205|
206| terms[key] = MulTable[b1][b2]
207| print(f'multiply3.product[{b1},{b2}]: {terms[key]}')
208|
209|
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|
217| for ix in range(len(buf)):
218| carry,value = divmod(buf[ix], 256)
219|
220| if carry:
221| buf[ix] = value
222| buf[ix+1] += carry
223|
224|
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|
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|
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|
259| ds1 = [int(d, base=0) for d in s1.split(',')]
260| ds2 = [int(d, base=0) for d in s2.split(',')]
261|
262|
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|
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|
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|
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|
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|
310|