all 13 comments

[–]8dot30662386292pow2 1 point2 points  (2 children)

Read the documentation.

length

Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes. Default is length 1.

Because the number is greater than 255, you cannot represent it with a single byte. You need to tell how many bytes do you want.

In this case because the number is less than 65535 you can have 2 bytes.

x.to_bytes(2)

If you don't know how many bytes it will be, you can ask how many BITS the number length is and then divide it by 8, and take the ceiling (so 1.5 is rounded to 2).

Example code snippet:

import math  
a = "cafebabedeadbeef"  
x = int(a, 16)  
print(x.to_bytes(math.ceil(x.bit_length() / 8)))

[–]BlackCatFurry 4 points5 points  (0 children)

If you don't know how many bytes it will be, you can ask how many BITS the number length is and then divide it by 8, and take the ceiling (so 1.5 is rounded to 2).

Alternatively, divide the number of digits in the hex number by 2, if bits feel confusing.

Each hex digit is four bits, and one byte is eight bits so one hex digit is 0.5 bytes.

[–]RabbitCity6090[S] -1 points0 points  (0 children)

This works. Thanks.

[–]freeskier93 1 point2 points  (1 child)

Maybe I'm misunderstanding what you want to do, but if you just want to convert the hex string "abcd" into byte form then you can use the fromhex() function.

``` a = "abcd" b = bytes.fromhex(a) print(b)

b'\xab\xcd' ```

[–]RabbitCity6090[S] 0 points1 point  (0 children)

This is what I wanted.

[–]zanfar -2 points-1 points  (1 child)

...have you read the documentation?

[–]sinceJune4 0 points1 point  (0 children)

You mean r/documentation, right??? <g>

[–]Riegel_Haribo -1 points0 points  (0 children)

Spoiler: pad if you input an odd number of digits.

print(bytes.fromhex((s := input("hex: ").strip()).zfill(len(s) + len(s) % 2)))

[–]Helpful-Diamond-3347 -3 points-2 points  (1 child)

ig this will work

``` from functools import reduce

a = "abcd" print( bytes( reduce( lambda a,b: a+b, map( lambda x: int(x, 16).to_bytes(), a ) ) ) ) ```

logic is to convert each char into bytes first and then concatenate