Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python bytes to C array (like xxd program"

In python3 I have some bytes. I want to export them to C source code. Outside python I use "xxd -i binary_file" command.

Example:

x = b'abc123'
print(bytes_to_c_arr(x))
# should output:
unsigned char x[] = { 0x61, 0x62, 0x63, 0x31, 0x32, 0x33 };

Is there ready method or handy one-liner? I can do away without type declaration, only bytes for contents would suffice.

like image 782
MateuszL Avatar asked May 29 '26 06:05

MateuszL


2 Answers

1. print([hex(i) for in x]) 

2. print(a.hex())

Results will be:

1. ['0x61', '0x62', '0x63', '0x31', '0x32', '0x33']
2. '616263313233'
like image 62
Aleksandr Fuze Avatar answered May 31 '26 20:05

Aleksandr Fuze


In case you want to use caps or not:

def bytes_to_c_arr(data, lowercase=True):
    return [format(b, '#04x' if lowercase else '#04X') for b in data]

x = b'abc123'
print("unsigned char x[] = {{{}}}".format(", ".join(bytes_to_c_arr(x))))
print("unsigned char x[] = {{{}}}".format(", ".join(bytes_to_c_arr(x, False))))

# output: unsigned char x[] = {0x61, 0x62, 0x63, 0x31, 0x32, 0x33}
#         unsigned char x[] = {0X61, 0X62, 0X63, 0X31, 0X32, 0X33}
like image 38
BPL Avatar answered May 31 '26 21:05

BPL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!