Convert Hex Chars into a String of Bits (Python or Ruby)
I have a microcontroller that returns a status response like this from an HTTP API:
<response><BS>026219AAF80F440206025019AAF816A944274480</BS></response>
The last two characters, in this case 80
, represent a hexadecimal value that I need to convert to a its binary bits 10000000
. Each bit is a flag that corresponds to a state on that piece of hardware.
For me to inspect each of the 8 bits, I need to take the string 80
(the whole response is a string and I just grab the last 2 characters) and turn it into a string representation of the binary 10000000
so I can inspect each of the 8 characters individua开发者_StackOverflowlly.
What's the best way to go about this? I'd like to do it in Python or Ruby, but I'm happy to learn the general technique of what I'm looking to do and then figure it out.
Note: I (obviously) don't have a CS background so much of this is foreign to me. I might be using the wrong nomenclature. Please feel free to correct me; I hope I got out the gist of what I'm looking for.
In Ruby:
yourbits = "026219AAF80F440206025019AAF816A944274480"[-2,2].to_i(16).to_s(2)
=> "10000000"
puts yourbits
10000000
=> nil
Explaining each step -- first, slice the string to get the last 2 characters:
"026219AAF80F440206025019AAF816A944274480"[-2,2]
=> '80'
Convert it to Integer:
"80".to_i(16)
=> 128
Back to string againg, in a binary representation:
128.to_s(2)
=> '10000000'
There's probably a better (or less confusing) way of doing it, but I can't imagine it right now.
If you're just testing individual bits then you can use it as a number instead.
>>> bool(int('80', 16) & 0x40)
False
>>> bool(int('80', 16) & 0x80)
True
Another option for decoding hex in Python is to use the decode
method:
data = "026219AAF80F440206025019AAF816A944274480".decode("hex")
the last two characters form the last byte, which can be accessed with data[-1]
. You can test individual bits using the &
operator as Ignacio demonstrates.
In python you can do this:
>>yourbits = str(bin(int("026219AAF80F440206025019AAF816A944274480"[-2:],16))[2:])
>>print yourbits
1000000
>>print yourbits[0]
'1'
[-2:]
is used to select "80" and [2:]
is for removing the "1b" in front of the binary representation of the string.
精彩评论