0

Is there a way to get python to print an even number of bytes when formatting hex? For example:

>>> hex(12)
'0xc'
>>> f'{12:#x}'
'0xc'
>>> f'{12:#X}'
'0XC'
>>> f'{12:X}'
'C'
>>> f'{12:x}'
'c'

Additionally, does python have a formatted that will separate bytes when there are multiple? For example:

>>> hex(1000)
'0x3e8' # 0e e8

Or would I need to create my own formatter for this?

1 Answer 1

1

You can format fixed length hex values in a string using a format specifier...

  • 0 - padded with 0's
  • 4 - number of digits
  • x - hex value

like this:

 '{:04x}'.format(12)

Which returns:

'000c'

AFAIK you'll need to have a custom format function to group by position. Maybe something like this:

hex_value = '0123456789abcdef'
' '.join(hex_value[i: i + 2] for i in range(0, len(hex_value), 2))

Which will return:

'01 23 45 67 89 ab cd ef'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.