0

What is the easiest way in Python to represent a number from 0 to 65535 using two bytes?

For example 300 in decimal is 0000000100101100 in binary and 012C in hexadecimal.

What I want to get as output when I get 300 is two bytes:

  • first is 00101100 (in binary representation)
  • second is 00000001 (in binary representation)

What is the easiest way to do it?

jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
Farseer
  • 3,808
  • 2
  • 37
  • 56

4 Answers4

4

I'm sure there is something better than this, though:

from struct import pack, unpack
unpack('BB', pack('H',300))
# gives (44, 1), the two bytes you were asking for

See python docs to see what the available letter codes are, also be mindful of byte order.

Ulrich Schwarz
  • 7,461
  • 1
  • 33
  • 46
1

You can get the low bits using & 255 (i.e. bitwise AND with 0b11111111):

>>> "{:08b}".format(300 & 255)
'00101100'

and the high bits by adding a bitwise shift:

>>> "{:08b}".format((300 >> 8) & 255)
'00000001'

For more information on the bitwise operators, see e.g. the Python wiki.

jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
1

I think you're looking for struct.pack:

>>> import struct
>>> i = 300
>>> struct.pack("H",i)
',\x01'

where the , is its ascii value - 44.

WeaselFox
  • 7,100
  • 7
  • 42
  • 73
1

As noted in this SO answer, you could do the following :

>>> my_hexdata = hex(300)                                     
>>> scale = 16 ## equals to hexadecimal                       
>>> num_of_bits = 16                                          
>>> mybin = bin(int(my_hexdata, scale))[2:].zfill(num_of_bits)
>>> mybin                                                     
'0000000100101100'                                            
>>> mybin[:8]                                                 
'00000001'                                                    
>>> mybin[8:16]                                               
'00101100'                                                    
Community
  • 1
  • 1
Jérôme Radix
  • 9,535
  • 4
  • 31
  • 39