I have an IP address R
(ie: "255.255.255.0"
) in string form that I'm hashing, and taking the first 4 bytes of that hash. I want to then convert that hashed result to binary format:
def H(R):
h = hashlib.sha256(R.encode('utf-8'))
return unhexlify(h.hexdigest())[0:4]
I tried doing the following, but I only get 30 bits instead of 32 (I remove the first 2 chars of the string because it's the 0b
prefix):
bin(struct.unpack('!I', H(R))[0])[2:]
How can I do this correctly? The result of H(R)
looks something like b',\xc3Z\xfb'. I've tried the methods here and none work with the format I'm converting from. Convert bytes to bits in python
- What I have: 4 bytes from the Hash of a 32 bit IP Address string, ie:
b',\xc3Z\xfb'
- What I'm trying to get: the 32 binary representation as a string, ie:
'10101010101010101010101010101010'