1

I am trying to convert an integer number into an array of byte strings.

def int2Hex():
    hex = '%08x' % 32
    bytes = []

    for i in range(0,4):
        bytes.append('0x' + hex[i*2: i*2 + 2])

    return bytes[::-1] #return in little endian

The above code works for positive numbers: ['0x00', '0x00', '0x00', '0x20']

but when I use a negative number I'll get something like this: ['0x-0', '0x00', '0x00', '0x20']

What I want for negative numbers is the 2's complement bytes. I am using python 2.

ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
Brian Thorpe
  • 317
  • 2
  • 13
  • What internal format are the "bytes" supposed to correspond to - some specific one or the system's native? Not in all platforms `int`s are 32-bit and big-endian. What about numbers that are out of range? – ivan_pozdeev Apr 12 '17 at 02:42
  • The task boils down to converting a signed integer to unsigned. – ivan_pozdeev Apr 12 '17 at 02:46

2 Answers2

3

You can use this:

def int2hex(number, bits):
    """ Return the 2'complement hexadecimal representation of a number """

    if number < 0:
        return hex((1 << bits) + number)
    else:
        return hex(number)

I hope you find it useful!

  • It should also have `assert number>>bits==0` - for numbers larger than the intended number of bits, the algorithm would return garbage. – ivan_pozdeev Apr 12 '17 at 03:04
  • Strictly speaking, it should return `['0x'+h[i:i+1] for i in range(0,len(h),2)]` where `h=("%%0%d"%(bits//4))%hex(...)` to conform to the problem statement. But that's an unrelated concern, so I don't mind it as it is. – ivan_pozdeev Apr 12 '17 at 03:09
3

If you make sure the number that is converted is always positive, and then mask the bottom 32 bits, your method can work.

Code:

OFFSET = 1 << 32
MASK = OFFSET - 1

def int2Hex(num):
    hex = '%08x' % (num + OFFSET & MASK)
    bytes = []

    for i in range(0, 4):
        bytes.append('0x' + hex[i * 2: i * 2 + 2])

    return bytes[::-1]  # return in little endian

print(int2Hex(20))
print(int2Hex(-20))

Results:

['0x14', '0x00', '0x00', '0x00']
['0xec', '0xff', '0xff', '0xff']
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135