Read Serial
Using PySerial the following program was created:
import serial
class comunicacao():
def __init__(self, porta, baud):
s = serial.Serial(porta, baud)
data = s.read(18)
data = data
print("Data: ", (data))
comunicacao('COM7', 57600)
It is receiving the number 10000 in decimal for tests, and the print output is: Data: b'\x020000000000002710\x03'
Because 2710 in HEX is 10000 in DEC.
Conversion
So trying to convert with the following ways:
print("Data: ", int(data, 16)) gives teh error:
print("Data: ", int(data, 16))
ValueError: invalid literal for int() with base 16: b'\x020000000000002710\x03'
With data = s.read(18).decode() the print output is Data: 0000000000002710 and trying to convert with int() gives the error:
print("Data: ", int(data, 16))
ValueError: invalid literal for int() with base 16: '\x020000000000002710\x03'
data = data.lstrip("0") with data = s.read(18).decode() didn't strip the leading zeroes.
And data = data.lstrip("0") with data = s.read(18) gives the error:
print("Data: ", (data.lstrip("0")))
TypeError: a bytes-like object is
required, not 'str'
Question
How to convert this data type (I think it is as ASCII, but is a HEX number) to DEC?
What about this:
data = '\x020000000000002710\x03'
# If we say that "\x02" opens an hexadecimal representation of an integer,
# and that "\x03" ends it, then for any number of ints in hex form in data, do:
converted = [int(x, 16) for x in data.replace("\x02", "").split("\x03") if x]
print(converted)
print(converted[0])
You get the list of all numbers you read from the port.
What this code does is that it removes the \x02 character so not to confuse the int() and then splits data by \x03.
Then it converts each element using the int(x, 16).
Using the classic way with added try statement would be more robust, if you expect some other data to be mixed in:
converted = []
for x in data.replace("\x02", "").split("\x03"):
try:
converted.append(int(x, 16))
except: pass
If "\x03" is not the int separator, you can use \x02 as one and combine the slicing to extract the number of needed digits.
If "\x03" is still the hexnum terminator, but the numbers do not follow eachother then use something like this:
data = '\x020000000000002710\x03blahblah\x0200ff\x03mmmm'
converted = []
for x in data.split("\x02"):
end = x.find("\x03")
if end==-1: continue
x = x[:end]
try:
converted.append(int(x, 16))
except: pass
Printing the converted now will give you the list:
[10000, 255]
As you can see, this will work even if hex numbers aren't equally padded with zeroes.
You can get the nice and reliablecode playing with similar code formulations.
Related
which is the easiest way that i can convert binary number into a hexadecimal number using latest python3?
i tried to convert a binary to number into a hexadecimal using hex() function. but it runs into few errors.
The code that i tried -:
choice = input("Enter Your Binary Number: ")
def binaryToHex(num):
answer = hex(num)
return(num)
print(binaryToHex(choice))
error that i faced :
Traceback (most recent call last):
File "e:\#Programming\Python\Number System Converter 0.1V\test.py", line 83, in <module>
print(binaryToHex(choice))
File "e:\#Programming\Python\Number System Converter 0.1V\test.py", line 80, in binaryToHex
answer = hex(num)
TypeError: 'str' object cannot be interpreted as an integer
EXAMPLE-:
111 --> 7
1010101011 --> 2AB
Use int to convert a string of digits to an integer. Use hex to convert that integer back to a hex string.
>>> hex(int('111', 2))
'0x7'
>>> hex(int('1010101011', 2))
'0x2ab'
# Python code to convert from Binary
# to Hexadecimal using int() and hex()
def binToHexa(n):
# convert binary to int
num = int(str(n), 2)
# convert int to hexadecimal
hex_num = hex(num)
return(hex_num)
You may use the Hex inbuilt function of Python 3. you can use this code too.
binary_string = input("enter binary number: ")
decimal_representation = int(binary_string, 2)
hexadecimal_string = hex(decimal_representation)
print("your hexadecimal string is: ",hexadecimal_string)
Method:
Considering you need '2AB' instead of '0x2ab'.
>>> Hex=lambda num,base:hex(int(num,base))[2:].upper()
>>> Hex('111',2)
'7'
>>> Hex('1010101011',2)
'2AB'
This is my code:
import serial
print('Arduino is setting up')
# Setting up the Arduino board
arduinoSerialData = serial.Serial('com4', 9600)
while True:
if arduinoSerialData.inWaiting() > 1:
myData = arduinoSerialData.readline()
myData = str(myData)
myData = myData.replace("b'", '')
myData = myData.replace("\\r\\n'", '')
myData1=myData
if myData1.find("a"):
myData1= myData1.replace("a",str(0))
if int(myData1)<100:
print(myData)
What this code does is it imports the data from the ultrasonic sensor thats attached to the arduino board, and prints it.myData is initially in bytes so I convert it to string, but I cannot seem to convert it to int.When I tried the above code, I get try this code, I get this error.Anyone know how to troubleshoot this?Thanks!
it seems that your bytes to string conversion is not correct. Why not try this:
1. Bytes to string conversion:
mydata = myData.decode("utf-8")
2. Eliminatinf trailing newline characters:
myData = myData.strip("\r\n")
Make sure that that the resulting string contains only numeric characters to get converted to int. You can do this check :
if mydata1.isdigit() and int(mydata1) < 100:
<your code>
If ur string contains float number,then u can perform do this:
if mydata1.replace(".", "").isdigit() and int(float(mydata1)) < 100:
If you give a string to int(), it needs to be an integer. If you instead have a non-integer, you can convert it with float() first, then use int() to turn that floating point value into an integer, as per the following transcript:
>>> print(int("328.94")) # Will not work.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '328.94'
>>> print(float("328.94")) # Convert string to float.
328.94
>>> print(int(float("328.94"))) # Convert string to float to int.
328
>>> print(int(float("328.94") + 0.5)) # Same but rounded.
329
That last one is an option if you want it rounded to the nearest integer, rather than truncated.
I have hex variable that I want to print as hex
data = '\x99\x02'
print (data)
Result is: ™
I want to the python to print 0x9902
Thank you for your help
Please check this one.
data = r'\x99\x02'
a, b = [ x for x in data.split(r'\x') if x]
d = int(a+b, base=16)
print('%#x'%d)
You have to convert every char to its number - ord(char) - and convert every number to hex value - '{:02x}'.format() - and concatenate these values to string. And add string '0x'.
data = '\x99\x02'
print('0x' + ''.join('{:02x}'.format(ord(char)) for char in data))
EDIT: The same but first string is converted to bytes using encode('raw_unicode_escape')
data = '\x99\x02'
print('0x' + ''.join('{:02x}'.format(code) for code in data.encode('raw_unicode_escape')))
and if you have already bytes then you don't have to encode()
data = b'\x99\x02'
print('0x' + ''.join('{:02x}'.format(code) for code in data))
BTW: Similar way you can convert to binary using {:08b}
data = '\x99\x02'
print(''.join('{:08b}'.format(code) for code in data.encode('raw_unicode_escape')))
I want to convert the string 400AM49L01 to a hexadecimal form (and then into bytes) b'x\34\x30\x30\x41\x4d\x34\x39\x4c\x30', so I can write it with pySerial.
I already tried to convert the elements of a list, which contains the single hexadecimals like 0x31 (equals 4), into bytes, but this will result in b'400AM49L01'.
device = '400AM49L01'
device = device.encode()
device = bytes(device)
device = str(binascii.hexlify(device), 'ascii')
code = '0x'
text = []
count = 0
for i in device:
if count % 2 == 0 and count != 0:
text.append(code)
code = '0x'
count = 0
code += i
count += 1
text.append((code))
result = bytes([int(x, 0) for x in text])
Really looking forward for your help!
The following code will give the result you expecting.
my_str = '400AM49L01'
"".join(hex(ord(c)) for c in my_str).encode()
# Output
# '0x340x300x300x410x4d0x340x390x4c0x300x31'
What is it doing ?
In order to convert a string to hex, you need to convert each character to the integer value from the ascii table using ord().
Convert each int value to hex using the function hex().
Concatenate all hex value generated using join().
Encode the str to bytes using .encode().
Regards!
Here is the I am trying:
import struct
#binary_data = open("your_binary_file.bin","rb").read()
#your binary data would show up as a big string like this one when you .read()
binary_data = '\x44\x69\x62\x65\x6e\x7a\x6f\x79\x6c\x70\x65\x72\x6f\x78\x69\x64\x20\x31\
x32\x30\x20\x43\x20\x30\x33\x2e\x30\x35\x2e\x31\x39\x39\x34\x20\x31\x34\x3a\x32\
x34\x3a\x33\x30'
def search(text):
#convert the text to binary first
s = ""
for c in text:
s+=struct.pack("b", ord(c))
results = binary_data.find(s)
if results == -1:
print ("no results found")
else:
print ("the string [%s] is found at position %s in the binary data"%(text, results))
search("Dibenzoylperoxid")
search("03.05.1994")
And this is the error I am getting:
Traceback (most recent call last):
File "dec_new.py", line 22, in <module>
search("Dibenzoylperoxid")
File "dec_new.py", line 14, in search
s+=struct.pack("b", ord(c))
TypeError: Can't convert 'bytes' object to str implicitly
Kindly, let me know what I can do to make it functional properly.
I am using Python 3.5.0.
s = ""
for c in text:
s+=struct.pack("b", ord(c))
This won't work because s is a string, and struct.pack returns a bytes, and you can't add a string and a bytes.
One possible solution is to make s a bytes.
s = b""
... But it seems like a lot of work to convert a string to a bytes this way. Why not just use encode()?
def search(text):
#convert the text to binary first
s = text.encode()
results = binary_data.find(s)
#etc
Also, "your binary data would show up as a big string like this one when you .read()" is not, strictly speaking, true. The binary data won't show up as a big string, because it is a bytes, not a string. If you want to create a bytes literal that resembles what might be returned by open("your_binary_file.bin","rb").read(), use the bytes literal syntax binary_data = b'\x44\x69<...etc...>\x33\x30'