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'
Related
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.
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'
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.
Am writing a program with python gui. that program concept is when we run the prgm it will ask to open one file(witch contains hexa decimal value as TASK.txt) with read mode.
am storing the data of one line in one variable.
how can i convert that data into ascii value. Am new to python. This is my code:
import binascii
import base64
from tkinter import *
from tkinter.filedialog import askopenfilename
def callback():
with open(askopenfilename(),'r') as r:
next(r)
for x in r:
z = str(x[1:-2])
if len(z) % 2:
z = '0' + 'x' + z
print(binascii.unhexlify(z))
a = Button(text='select file', command=callback)
a.pack()
mainloop()
This is the error I am getting:
Exception in Tkinter callback
Traceback (most recent call last):
File "D:\python sw\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:\Users\LENOVO\Downloads\hex2.py", line 16, in callback
print(binascii.unhexlify(z))
binascii.Error: Non-hexadecimal digit found"""
Just reread your question correctly, new answer:
Do not prefix with 0x since it does not work with unhexlify and won't even make the string-length even.
You need an even string length, since each pair of hex-digits represent one byte (being one character)
unhexlify returns a byte array, which can be decoded to a string using .decode()
As pointed out here you don't even need the import binascii and can convert hex-to-string with bytearray.fromhex("7061756c").decode()
list(map(lambda hx: bytearray.fromhex(hx).decode(),"H7061756c H7061756c61".replace("H","").split(" ")))
Returns ['paul', 'paula']
What I wrote before I thoroughly read your question
may still be of use
As PM 2Ring noted, unhexilify only works without prefixes like 0x.
Your hex-strings are separated by spaces and are prefixed with H, which must be removed. You already did this, but I think this can be done in a nicer way:
r = "H247314748F8 HA010001FD" # one line in your file
z_arrary = data.replace("H","").split(" ")
# this returns ['247314748F8','A010001FD']
# now we can apply unhexlify to all those strings:
unhexed = map(binascii.unhexlify, z_array)
# and print it.
print(list(unhexed))
This will throw you an Error: Odd-length string. Make sure you really want to unhexilify your data. As stated in the docs you'll need an even number of hexadecimal characters, each pair representing a byte.
If you want to convert the hexadecimal numbers to decimal integers numbers instead, try this one:
list(map(lambda hx: int(hx,16),"H247314748F8 HA010001FD".replace("H","").split(" ")))
int(string, base) will convert from one number system (hexadecimal has base 16) to decimal (with base 10).
** Off topic **
if len(z) % 2:
z = '0' + 'x' + z
Will lead to z still being of uneven length, since you added an even amount of characters.
I'm able to convert Hex data to Decimal with:
file = open("my_text.txt", "r+")
data = input("Type Hex: ")
hex = int(data, 16)
str(hex)
print(str(hex))
file.write(str(hex))
file.close()
input("close: ")
But how can I convert Decimal data, like a number or a sentence, to Hex? Also, is it possible to write data to a hexadecimal offset?
How about something like this?
>>> print(hex(257))
0x101
>>> for ch in b'abc':
... print(hex(ch))
...
0x61
0x62
0x63
BTW, assigning to a variable called "hex" occludes the built-in function - it's best to avoid that.
HTH