Python - Decoding Binary to Boolean
binary, boolean, python, struct, unpack
Solution
from struct documentation:
The '?' conversion code corresponds to the _Bool type defined by C99. If this type is not available, it is simulated using a char. In standard mode, it is always represented by one byte.
The `?` type will be unpacked as a bool type:
>>> type(struct.unpack('?','c')[0])
<type 'bool'>
Any value other than null character (`'\0'`) will be True. So you can follow the suggestion from Jan Vlcinsky. Your solution depends on what data you receive. If a null byte means False and other byte True, then you can continue using `?` unpacking as a simplest solution.
So to check if your first boolean in a message is true use this test:
messageEnaKill = struct.unpack('!HHLfIL??', messageEnaKill_raw)
if(messageEnaKill[7]==True):
# do something
Problem
I'm trying to receive some data with sockets, and then unpack the data to work on it. In input, i have a binary string : "MsgID - Sender - Size - Time1 - Time2 - Resrv - bool1 - bool2" Here is the format : "H - H - L - f - I - L - 'bool' - 'bool'" When I receive the data, I have to unpack it with this line : ``` messageEnaKill = struct.unpack('!HHLfIL??', messageEnaKill_raw) ``` And then I have to work on the boolean values (the last 2 ones). The fact is I don't know the format for boolean values, is it a char ('c') or something ? My second problem is that I have to check the binary boolean if it is True or False. How can I do that ? is this code true : ``` if msg[0] == bin(True): ``` considering "msg[0]" the boolean data from the "unpack". Thanks for the support !