I want to take an integer (that will be <= 255), to a hex string representation
e.g.: I want to pass in 65 and get out '\x41', or 255 and get '\xff'.
I've tried doing this with the struct.pack('c',65), but that chokes on anything above 9 since it wants to take in a single character string.
You are looking for the chr function.
You seem to be mixing decimal representations of integers and hex representations of integers, so it's not entirely clear what you need. Based on the description you gave, I think one of these snippets shows what you want.
>>> chr(0x65) == '\x65'
True
>>> hex(65)
'0x41'
>>> chr(65) == '\x41'
True
Note that this is quite different from a string containing an integer as hex. If that is what you want, use the hex builtin.
This will convert an integer to a 2 digit hex string with the 0x prefix:
strHex = "0x%0.2X" % integerVariable
What about hex()?
hex(255) # 0xff
If you really want to have \ in front you can do:
print '\\' + hex(255)[1:]
Let me add this one, because sometimes you just want the single digit representation
( x can be lower, 'x', or uppercase, 'X', the choice determines if the output letters are upper or lower.):
'{:x}'.format(15)
> f
And now with the new f'' format strings you can do:
f'{15:x}'
> f
To add 0 padding you can use 0>n:
f'{2034:0>4X}'
> 07F2
NOTE: the initial 'f' in f'{15:x}' is to signify a format string
Try:
"0x%x" % 255 # => 0xff
or
"0x%X" % 255 # => 0xFF
Python Documentation says: "keep this under Your pillow: http://docs.python.org/library/index.html"
For Python >= 3.6, use f-string formatting:
>>> x = 114514
>>> f'{x:0x}'
'1bf52'
>>> f'{x:#x}'
'0x1bf52'
If you want to pack a struct with a value <255 (one byte unsigned, uint8_t) and end up with a string of one character, you're probably looking for the format B instead of c. C converts a character to a string (not too useful by itself) while B converts an integer.
struct.pack('B', 65)
(And yes, 65 is \x41, not \x65.)
The struct class will also conveniently handle endianness for communication or other uses.
With format(), as per format-examples, we can do:
>>> # format also supports binary numbers
>>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
'int: 42; hex: 2a; oct: 52; bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
Note that for large values, hex() still works (some other answers don't):
x = hex(349593196107334030177678842158399357)
print(x)
Python 2: 0x4354467b746f6f5f736d616c6c3f7dL
Python 3: 0x4354467b746f6f5f736d616c6c3f7d
For a decrypted RSA message, one could do the following:
import binascii
hexadecimals = hex(349593196107334030177678842158399357)
print(binascii.unhexlify(hexadecimals[2:-1])) # python 2
print(binascii.unhexlify(hexadecimals[2:])) # python 3
(int_variable).to_bytes(bytes_length, byteorder='big'|'little').hex()
For example:
>>> (434).to_bytes(4, byteorder='big').hex()
'000001b2'
>>> (434).to_bytes(4, byteorder='little').hex()
'b2010000'
This worked best for me
"0x%02X" % 5 # => 0x05
"0x%02X" % 17 # => 0x11
Change the (2) if you want a number with a bigger width (2 is for 2 hex printned chars) so 3 will give you the following
"0x%03X" % 5 # => 0x005
"0x%03X" % 17 # => 0x011
Also you can convert any number in any base to hex. Use this one line code here it's easy and simple to use:
hex(int(n,x)).replace("0x","")
You have a string n that is your number and x the base of that number. First, change it to integer and then to hex but hex has 0x at the first of it so with replace we remove it.
I wanted a random integer converted into a six-digit hex string with a # at the beginning. To get this I used
"#%6x" % random.randint(0xFFFFFF)
As an alternative representation you could use
[in] '%s' % hex(15)
[out]'0xf'
Related
Can you please explain why I am getting an empty string after converting int value to char?
Python Code:
s = "10"
for c in s:
#doing rotation of number by 2
val = (ord(c) + 2 - 48)%10
print(type(val), val)
#Convert int to str
val = chr(val)
print(type(val), val)
Output:
>> <class, int> 3
>> <class, str>
>> <class, int> 2
>> <class, str>
Your code is converting the numbers you get after your "rotation" into strings, but not into the digits you want to have. If you want to use chr to convert an integer between 0 and 9 into its digit representation, you need to add back in the offset to '0' in Unicode, 48. You had to subtract that out earlier, when you converted the digit into its codepoint, now it's time to add it back on.
Try:
val = chr(val + 48)
Actually you don't get an empty string, but a string, which contains no printable character, since chr(2), chr(3) correspond to STX and ETX control characters.
You might consider using strinstead of chr.
I have an hexa string that I want to convert to a numpy array of int.
I don't want to use for loops because looping through numpy arrays is not advised.
So I do the following :
vector = np.fromstring( s.decode('hex'), dtype=np.uint8 )
If for example s = 'a312', s.decode('hex') returns '\xa3\x12' which is correct.
But if s = 'a320', s.decode('hex') returns '\xa3 ' which seems a little bit weird as first sight because I expect '\xa3\x20'.
Can you help me ?
The point is that a binary string in Pyhon is represented as its ASCII equivalent.
The equivalent of '\x20' is a space, as one can see in the ASCII table:
Hex Dec ASCII
20 32 (space)
If you write '\x20' in the terminal, it will print a space:
>>> '\x20'
' '
>>> 'a320'.decode('hex') == '\xa3\x20'
True
Note that this is only an aspect of representation: behind the curtains, the binary string contains the 0010 0000 binary value.
I am having string of four hex numbers like:
"0x00 0x01 0x13 0x00"
which is equivalent to 0x00011300. How i can convert this hex value to integer?
Since you are having string of hex values. You may remove ' 0x' from the string to get the single hex number string. For example:
my_str = "0x00 0x01 0x13 0x00"
hex_str = my_str.replace(' 0x', '')
where value hold by hex_str will be:
'0x00011300' # `hex` string
Now you may convert hex string to int as:
>>> int(hex_str, 16)
70400
>>> s="0x00 0x01 0x13 0x00"
>>> a=0
>>> for b in s.split():
... a = a*256 + int(b,16)
...
>>> a
70400
>>> hex(a)
'0x11300'
The answer is here Convert hex string to int in Python.
Without the 0x prefix, you need to specify the base explicitly, otherwise there's no way to tell:
x = int("deadbeef", 16)
With the 0x prefix, Python can distinguish hex and decimal automatically.
print int("0xdeadbeef", 0)
3735928559
print int("10", 0)
10
(You must specify 0 as the base in order to invoke this prefix-guessing behavior; omitting the second parameter means to assume base-10. See the comments for more details.)
I'm currently reading bytes from a file and I want to put two of these bytes into a list and convert them into an integer. Say the two bytes I want to read are \x02 and \x00 I want to join these bytes together before I convert them into an integer such as 0x0200 but am having difficulty doing so as I cannot remove the \x from the bytes.
I've tried using: .replace('\\x', '') though this doesn't work as python treats the bytes as one object rather than a list. I've also considered using struct although I'm unsure whether this would work in my situation.
It's also not possible to iterate through each byte and remove the first two items as python still treats the entire byte as one object.
Here is the list I have after appending it with both bytes:
While it looks like two strings, they do not behave as strings. I then iterated over the list using:
for x in a:
print a
The two lines below the list are the outputs of 'print a' (a blank space & special character). As you can see they do not print as normal strings.
Below is a code snippet showing how I add the bytes to the array, nothing complicated (test being the array in this case).
for i in openFile.read(512):
....
....
elif 10 < count < 13:
test.insert(0, i[0:])
You could use ord to extract each character's numeric value, then combine them with simple arithmetic.
>>> a = '\x02'
>>> b = '\x00'
>>> c = ord(a)*256 + ord(b)
>>> c == 0x0200
True
>>> print hex(c)
0x200
An alternate way to do this for standard-length types is to use the struct module to convert from strings of bytes to Python types.
For example:
>>> import struct
>>> byte_arr = ['\x02', '\x00']
>>> byte_str = ''.join(byte_arr)
>>> byte_str
'\x02\x00'
>>> num, = struct.unpack('>H', byte_str)
>>> num
512
In this example, the format string '>H' indicates a big-endian unsigned 2-byte integer. Other format strings can be used to specify other sizes, endianness, and signed/unsigned status.
new_str=str(your_byte_like_object).split('\\x')
print("".join(new_str))
You can convert the byte object to str and split it separator use \x
and you get a list and join it.
that's all.
output is like this:
eigioer #text
b'0\x1e\xd7\xe8\xdf\xc1\xd7\x90o3`mD\x92U\xf5\xca\xe7l\xe5"TM' #raw byte
["b'0", '1e', 'd7', 'e8', 'df', 'c1', 'd7', '90o3`mD', '92U', 'f5', 'ca', 'e7l', 'e5"TM\''] #list
b'01ed7e8dfc1d790o3`mD92Uf5cae7le5"TM' #after joining
I had the same problem. I had a "bytes" object and I needed to remove the \xs to be able to upload my file to Cassandra, and all I needed to do was to use this:
my_bytes.hex()
We know that it always starts with \x, and the 'it' is a string. So we can just do...
>>> num = "\\x02"
>>> num = num[2:]
>>> print num
02
Update:
>>> num = [r"\x02", r"\x20"]
>>> num = [ n[2:] for n in num ]
>>> num
['02', '20']
Does anyone know how to get a chr to hex conversion where the output is always two digits?
for example, if my conversion yields 0x1, I need to convert that to 0x01, since I am concatenating a long hex string.
The code that I am using is:
hexStr += hex(ord(byteStr[i]))[2:]
You can use string formatting for this purpose:
>>> "0x{:02x}".format(13)
'0x0d'
>>> "0x{:02x}".format(131)
'0x83'
Edit: Your code suggests that you are trying to convert a string to a hexstring representation. There is a much easier way to do this (Python2.x):
>>> "abcd".encode("hex")
'61626364'
An alternative (that also works in Python 3.x) is the function binascii.hexlify().
You can use the format function:
>>> format(10, '02x')
'0a'
You won't need to remove the 0x part with that (like you did with the [2:])
If you're using python 3.6 or higher you can also use fstrings:
v = 10
s = f"0x{v:02x}"
print(s)
output:
0x0a
The syntax for the braces part is identical to string.format(), except you use the variable's name. See https://www.python.org/dev/peps/pep-0498/ for more.
htmlColor = "#%02X%02X%02X" % (red, green, blue)
The standard module binascii may also be the answer, namely when you need to convert a longer string:
>>> import binascii
>>> binascii.hexlify('abc\n')
'6162630a'
Use format instead of using the hex function:
>>> mychar = ord('a')
>>> hexstring = '%.2X' % mychar
You can also change the number "2" to the number of digits you want, and the "X" to "x" to choose between upper and lowercase representation of the hex alphanumeric digits.
By many, this is considered the old %-style formatting in Python, but I like it because the format string syntax is the same used by other languages, like C and Java.
The simpliest way (I think) is:
your_str = '0x%02X' % 10
print(your_str)
will print:
0x0A
The number after the % will be converted to hex inside the string, I think it's clear this way and from people that came from a C background (like me) feels more like home