[Tutor] Struct the solution for Hex translation
Alan Gauld
alan.gauld at btinternet.com
Wed Feb 21 21:51:23 CET 2007
"Johan Geldenhuys" <johan at accesstel.co.za> wrote
> On the struct module, How can I het the binary 1's
> and 0's of the Hex value? Let say I want to get the
> 8 bit value of '\xe2', can I use struct to convert
> that into binary code
No, struct converts your data into a string of bytes and
provides a way to view a string representation of those
bytes.
But you can use bitmasks to get at the individual bits.
(See my Using the OS topic for a box on bitwise operators
and use of bitmasks.)
Basically you want to bitwise AND the data with a mask
containing just a one in the 8th position
(since 1& 0 = 0 and 1& 1 = 1)
Thus 10000000 = 80 hex. So:
>>> for n in range(125,130):
... print n,':',n&0x80
...
125 : 0
126 : 0
127 : 0
128 : 128 <--- the one is set so the & returns the mask
129 : 128
>>>
> so that I get 8 binary bits as a string?
See the bin() function in the sidebar in my topic for a function to
display a number in its binary form.
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list