1

I need to split a four digit string to two hexadecimal numbers.

Eg: string = "ABCD" expected output = 0xAB 0xCD

I tried these statements:

>>data = "0000"
>>[byte1, byte2] = [data[:2], data[2:]]
>>byteInt = int(byte1,16)
>>byteHex = format(byteInt,'0#4x')
>>print byteHex

I am getting the error, "ValueError: Invalid conversion specification" at the line "byteHex = format(byteInt,'0#4x')"

1 Answer 1

1

The leading zero in the format specification is not needed since you have not specified any alignment:

format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]

fill is conditioned on alignment:

>>> byteHex = format(byteInt,'#4x')
>>> byteHex
' 0x0'

To use the optional fill in the format specification, you should specify an alignment:

>>> byteHex = format(byteInt,'0>#4x') # left align
>>> byteHex
'0x00'
Sign up to request clarification or add additional context in comments.

5 Comments

It's working. Can you suggest me where I can learn more about 'format()'?
There is another issue. If I use the "byteHex = format(byteInt,'0<#4x')", when the value of byteInt is 4, the output is 0x40, instead of 0x04. Can you help with that?
Sorry, I missed the arrow for left align. Should have been >.
I referred the link that you have sent. I found out that I should use '= ' instead. It is working now.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.