You have an ASCII string representing a 128-bit unsigned integer number n, i.e. 0 <= n < 2^128.
Give an algorithm to extract the most significant 32 bits of the binary representation of n and return them as the unsigned 32 bit integer they encode.
What is a fast way to do this, i.e. something better than implementing your own big number division and modulo 2 operations.
Assume a 32bit machine, i. e. you don’t have 64-bit built-in types.
Examples:
For brevity, let’s take 4 bit integers and extract the leading 2 bits:
2(0010) –> 0(00)
7(0111) –> 1(01)
8(1000) –> 2(10)
13(1101) –> 3(11)
This is NOT a homework question. Updating my algo skills for an interview.
I don’t see a more efficient way than to simply emulate (a limited form of) 128 bit arithmetic.
Let’s say we have a function
mul10add(a, b)which calculates10*a + band returns the lower 32 bits of the answer together with a carry value. If we have 64-bit arithmetic it can be implemented as (in pseudo-code):Now, we take the normal decimal-to-binary algorithm and represent the 128-bit number
nwith four 32-bit wordsx,y,zandwsuch thatn = x*2^96 + y*2^64 + z*2^32 + w. We can then chain calls tomul10addtogether to perform the equivalent ofn = 10*n + digitToInt(decimal[i]).We don’t actually need a 64-bit architecture to implement
mul10add, however. On x86 we have themulinstruction which multiplies two 32-bit numbers to get a 64-bit number with the upper 32 bits stored inedxand the lower ones ineax. There’s also theadcinstruction, which adds two numbers but includes the carry from a previousadd. So, in pseudo-assembly: