I am trying to get the binary 0 and 1s of a string so I can transfer it using Li-Fi technology, basically using a led on a raspberry pi to turn on if it is a 1 and turn off if it is a 0. When I print "bit" it prints the 0 and 1s, but when I use if statements, nothing happens, any idea why?
test_str = "hello world"
res = ''.join(format(ord(i), '08b') for i in test_str)
for bit in res:
#print(bit) //works as I want it
if bit == 1:
print ("x")
elif bit == 0:
print ("y")
CodePudding user response:
Because res
is a string, not a set of integers. You would need bit == '1'
and bit == '0'
.
However, you don't have to go through strings at all.
for c in test_str:
for bit in range(8):
if ord(c) & (1 << bit):
print("x")
else:
print("y")
CodePudding user response:
You can just use encode method of the string object that encodes your string as a bytes object using the passed encoding type. You just need to make sure you pass a proper encoding to encode function.
In [9]: "hello world".encode('ascii')
Out[9]: b'hello world'
In [10]: byte_obj = "hello world".encode('ascii')
In [11]: byte_obj
Out[11]: b'hello world'
In [12]: byte_obj[0]
Out[12]: 104
Otherwise, if you want them in form of zeros and ones --binary representation-- as a more pythonic way you can first convert your string to byte array then use bin function within map :
>>> st = "hello world"
>>> map(bin,bytearray(st))
['0b1101000', '0b1100101', '0b1101100', '0b1101100', '0b1101111', '0b100000', '0b1110111', '0b1101111', '0b1110010', '0b1101100', '0b1100100']
Or you can join it:
>>> ' '.join(map(bin,bytearray(st)))
'0b1101000 0b1100101 0b1101100 0b1101100 0b1101111 0b100000 0b1110111 0b1101111 0b1110010 0b1101100 0b1100100'
You can then slice the resulting strings to remove the starting Ob
from them, and iterate over each character (0
's and 1
's) and handle them to print either x
or y
as appropriate.
test_str = "hello world".encode("ascii")
x = map(bin, bytearray(test_str))
for each_char in x:
each_char = each_char[2:]
for each_bit in each_char:
if each_bit == "1":
print("x")
else:
print("y")