2

I wish to convert a number like 683550 (0xA6E1E) to b'\x1e\x6e\x0a\x00', where the number of bytes in the array is a multiple of 2 and where the len of the bytes object is only so long as it needs to be to represent the number.

This is as far as I got:

"{0:0{1}x}".format(683550,8)

giving:

'000a6e1e' 
3
  • docs.python.org/3/library/struct.html#format-strings Commented Aug 24, 2016 at 20:53
  • What's up with the crazy byte order? That's not big-endian or little-endian. Commented Aug 24, 2016 at 21:01
  • @user2357112 I'm sorry. The reason it was messed up was because I was using "hexdump -x" to view the bytes in the file. Without the -x it makes more sense. Commented Aug 25, 2016 at 18:41

2 Answers 2

2

Use the .tobytes-method:

num = 683550
bytes = num.to_bytes((num.bit_length()+15)//16*2, "little")
Sign up to request clarification or add additional context in comments.

4 Comments

Outputting [hex(i) for i in t] for your answer gives ['0x1e', '0x6e', '0xa', '0x0']. I'm looking for ['0x6e', '0x1e', '0x0','0xa']
so you really want this mixed little-big-endian stuff. So see my updated answer.
I'm sorry @Daniel, your original answer was indeed correct. I was using "hexdump -x" to view the file which was switching things around. I've edited my question with the correct bytes.
so back again, again.
0

Using python3:

def encode_to_my_hex_format(num, bytes_group_len=2, byteorder='little'):
  """
  @param byteorder can take the values 'little' or 'big'
  """
  bytes_needed = abs(-len(bin(num)[2: ]) // 8)

  if bytes_needed % bytes_group_len:
    bytes_needed += bytes_group_len - bytes_needed % bytes_group_len

  num_in_bytes = num.to_bytes(bytes_needed, byteorder)
  encoded_num_in_bytes = b''

  for index in range(0, len(num_in_bytes), bytes_group_len):
    bytes_group = num_in_bytes[index: index + bytes_group_len]

    if byteorder == 'little':
      bytes_group = bytes_group[-1: -len(bytes_group) -1 : -1]

    encoded_num_in_bytes += bytes_group

  encoded_num = ''

  for byte in encoded_num_in_bytes:
    encoded_num += r'\x' + hex(byte)[2: ].zfill(2)

  return encoded_num

print(encode_to_my_hex_format(683550))

2 Comments

You need to output bytes not a string.
Then just return encoded_num_in_bytes instead of encoded_num in the function.

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.