Python convert a string containing hex to actual hex - python

I have a hex string, but i need to convert it to actual hex.
For example, i have this hex string:
3f4800003f480000
One way I could achieve my goal is by using escape sequences:
print("\x3f\x48\x00\x00\x3f\x48\x00\x00")
However, I can't do it this way, because I want create together my hex from multiple variables.
My program's purpose is to:
take in a number for instance 100
multiply it by 100: 100 * 100 = 10000
convert it to hex 2710
add 0000
add 2710 again
add 0000 once more
Result I'm expecting is 2710000027100000. Now I need to pass this hexadecimal number as argument to a function (as hexadecimal).

In Python, there is no separate type as 'hex'. It represents the hexadecimal notation of the number as str. You may check the type yourself by calling it on hex() as:
# v convert integer to hex
>>> type(hex(123))
<type 'str'>
But in order to represent the value as a hexadecimal, Python prepends the 0x to the string which represents hexadecimal number. For example:
>>> hex(123)
'0x7b'
So, in your case in order to display your string as a hexadecimal equivalent, all you need is to prepend it with "0x" as:
>>> my_hex = "0x" + "3f4800003f480000"
This way if you probably want to later convert it into some other notation, let's say integer (which based on the nature of your problem statement, you'll definitely need), all you need to do is call int with base 16 as:
>>> int("0x3f4800003f480000", base=16)
4559894623774310400
In fact Python's interpreter is smart enough. If you won't even prepend "0x", it will take care of it. For example:
>>> int("3f4800003f480000", base=16)
4559894623774310400
"0x" is all about representing the string is hexadecimal string in case someone is looking/debugging your code (in future), they'll get the idea. That's why it is preferred.
So my suggestion is to stick with Python's Hex styling, and don't convert it with escape characters as "\x3f\x48\x00\x00\x3f\x48\x00\x00"
From the Python's hex document :
Convert an integer number to a lowercase hexadecimal string prefixed with “0x”. If x is not a Python int object, it has to define an index() method that returns an integer.

try binascii.unhexlify:
Return the binary data represented by the hexadecimal string hexstr.
example:
assert binascii.unhexlify('3f4800003f480000') == b"\x3f\x48\x00\x00\x3f\x48\x00\x00"

>>> hex(int('3f4800003f480000', 16))
'0x3f4800003f480000'

Related

Convert a decimal number into a byte size of 8 bit array

x = 64
var_in_bin_format = bin(64)
print(var_in_bin_format)
#Output
#0b1000000
#Desired Output -- > should always be in 8 bit format
#0b01000000
def call_another_api(var_in_bin_format):
pass
In Python, I need to call an API that expects its parameter to be always in 8 bit format regardless of the value of the decimal number?
I am not that good in bit manipulation so I am thinking if there is something I can do here?
How can I do this? I cannot use the format() function as it will convert the value into a string representation and the API that I am calling will alert me that it is not in the correct format.
Even though you say that you can't use format() because it returns a string, I'm going to post this because that's also what bin() does. bin(x) is equivalent to format(x, '#b'). I'd guess that you haven't added the '#', which means you won't have '0b' leading the value.
The Python 3 documentation for bin() actually gives a pretty strong hint about how you might do this, using format instead.
If you know that the value passed will not be negative, you can use the format string '#010b':
format(x, '#010b')
Breaking this down:
'b' means that the number will be a string binary representation.
'10' means that the entire string will be 10 characters long, two for '0b' and 8 for the value.
'0' makes it pad with '0' instead of ' '.
'#' will add the '0b' prefix, as done by bin().
Note that this assumes that the number is an integer in the range [0, 255]. Integers outside this range will generate valid representations, but will not match the format expected, and may have a leading '-'. Objects of type float can not be converted with the 'b' format code. I assume that these are not problems, given what your intended output is, but it might be a good idea to add an explicit check to throw a ValueError if the value is less than 0 or greater than 255.
If you're in Python 3.6+, you could also use f-strings:
f'{x:#010b}'
Is is not possible to convert all decimal numbers to 8 bit. You can only convert numbers from 0 to 255 in 8 bits.

Why Does Hex() Function returns a string instead an int hex?

I dont know why Hex function returns a string like '0x41' instead 0x41
I need to convert an ASCII value into a hex. But i want in 0x INT format, not into a '0x' string.
ascii = 360
hexstring = hex(ascii)
hexstring += 0x41 # i cant do this because hexstring is a string not a int hex
How i can get a int hex??
thanks
There is no int hex object. There is only an alternative syntax to create integers:
>>> 0x41
65
You could have used 0o1010 too, to get the same value. Or use 0b1000001 to specify it in binary; they are all the exact same numeric value to Python; they are all just different forms to specify an integer value in your code.
Simply keep ascii as an integer and sum your hex notation values with that:
>>> ascii = 360
>>> ascii += 0x41
>>> ascii
425
hex() produces a string that can be interpreted by a Python program in the same manner, and is usually used when debugging code or quick presentation output (but you should use format(number, 'x') if you want to produce end-user output without the 0x prefix). It is not needed to work with integers.

How to treat a hex as string?

I have some hex number such as 0x61cc1000 and I want to input them to a function which only takes string. I want to treat the hex numbers as strings without any change.
If I use str() function it converts it to int and then treats it as string. But I want to keep the original hex value.
Your problem is that you're using str:
>>> str(0x61cc1000)
'1640763392' # int value of the hex number as a string
That's because first 0x61cc1000 is evaluated as an int, then str performed on the resulted int.
You want to do:
"{0:x}".format(0x61cc1000)
Or
'{:#x}'.format(0x61cc1000)
As already stated in other answer, you can simply:
>>> hex(0x61cc1000)
'0x61cc1000'
See 6.1.3.1. Format Specification Mini-Language for details.
If you want the hex string representation of any integer, just pass it through the hex built-in.
>>> n = 0x61cc1000
>>> n
1640763392
>>> hex(n)
'0x61cc1000'
If you want to have 0x at the beginning you may use #x format like this:
'{:#x}'.format(74954)

Convert hexadecimal notation literally to string or vice versa

The function I'm writing gets a checksum (format: '*76') as a string (isolated from an NMEA string). This checksum in string format is called 'Obs' (Observed from string). It then computes the checksum from the rest of the string and gets that answer as hex (Terminal: 0x76), this will be called 'Com' (Computed from string). Now I need to convert one to the other to compare them agains each other.
I've tried stuff like:
HexObs = hex(Obs) #with Obs as '0x76' and '0*76'
Which gives me an error.
and
StrCom = str(Com)
Which gives: '118'
There were no previous questions in which I recognised my question.
Does anyone know how to convert one to the other? Tnx in advance.
I think you're problem is getting the original into an actual hex form
tobs = '76'
obs = hex(int('0x' + tobs, 16))
that will give you an actual hex value to compare
alternately you could use:
tobs = '76'
com = '0x76'
tcom = com[2:]
then compare tobs & tcom
To go from a string hex representation, use:
>>> int('0x76', 16)
118
The second argument is the base.
To go from an integer to a string hex representation, use:
>>> hex(118)
'0x76'

How do I convert a string of bits to a hex string in Python?

I have a bit-string of 32 characters that I need to represent as hexadecimal in Python. For example, the string "10000011101000011010100010010111" needs to also be output as "83A1A897".
Any suggestions on how to best go about this in Python?
To format to hexadecimal you can use the hex function:
>>> hex(int('10000011101000011010100010010111', 2))
0x83a1a897
Or to get it in exactly the format you requested:
>>> '%08X' % int('10000011101000011010100010010111', 2)
83A1A897
>>> binary = '10010111'
>>> int(binary,2)
151
>>> hex(int(binary,2))
'0x97'
I hope this helps!
You can do this very easy with build in functions.
The first thing you want to do is convert your binary to an integer:
>> int("1010",2)
10
The second step then would be to represent this as hex:
>> "%04X" % int("1010",2)
'000A'
in case you don't want any predefined length of the hex string then just use:
>> "%X" % int("1010",2)
'A'
>> "0x%X" % int("1010",2)
'0xA'
To read in a number in any base use the builtin int function with the optional second parameter specifying the base (in this case 2).
To convert a number to a string of its hexadecimal form just use the hex function.
>>> number=int("10000011101000011010100010010111",2)
>>> print hex(number)
0x83a1a897L
Well we could string format just like Mark Byers said.Or in other way we could string format in another method like given below:
>>> print('{0:x}'.format(0b10000011101000011010100010010111))
83a1a897
To make the alphabets between the hex in upper case try this:
>>> print('{0:X}'.format(0b10000011101000011010100010010111))
83A1A897
Hope this is helpful.

Categories