简体   繁体   中英

convert bytes into hexadecimal in python

I am trying to multiply two data of bytes data type using python by trying to converting them into hexadecimal values. but it seems that the hex() function is not working. Can you please help me on that. Below is my code (x and y are our data of type bytes)

data=bytes.hex(x) * bytes.hex(y)

I am getting the error: TypeError:'str' object cannot be interpreted as an integer

by trying

data = hex(x) * hex(y)

the error become: TypeError:'bytes' object cannot be interpreted as an integer

Can anyone help please?

hex(my_var) returns a string. To do math you need to convert your variables to int:

x_int = int(x, base=16)
y_int = int(y, base=16)

decimal_value = x_int * y_int # integer
hex_value = hex(decimal_value) # string

data = hex(x) * hex(y)

This doesn't work because the hex() function expects an int as an argument and outputs a string.

In Python 3, you can do the following (interprets bytes as base 10)

data = hex(int(x)*int(y))

I see in the comments below your question that you have examples of your x and y values - you have some very large numbers to process if you interpret the bytes objects as arbitrary length integers. Not sure this is what you want, but this will do conversion of bytes to/from integer values.

>>> int_x = int.from_bytes(x, 'big')              # From bytes to int.
>>> int_y = int.from_bytes(y, 'big')
>>> int_z = int_x * int_y                         # int_z as an integer.
>>>
>>> # Converting int_z to a bytes object:
>>>
>>> bytes_length = (int_z.bit_length() + 7) // 8
>>>
>>> z = int_z.to_bytes(bytes_length, 'big')

If you want them interpreted as little endian, replace 'big' with 'little'.

If your y value is already an int type, which it looks like in your comment, then don't convert it before multiplying:

>>> int_x = int.from_bytes(x, 'big')
>>> int_y = y
>>> int_z = int_x * int_y
>>> z     = int_z.to_bytes(bytes_length, 'big')

The first parameter to int.to_bytes() is the length of the bytes object to create. There are other ways to calculate this value, but the way I included is the fastest method out of 3 that I timed.

If all you wanted to do was convert a bytes object to its hex string representation ( z below is treated as a bytes object):

>>> hex_z = '0x' + ''.join(hex(b)[2:] for b in z)

Or to convert an int to a hex string:

>>> hex_z = hex(int_z)

hex() can handle very large integers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM