0

I have a value out of I²C register which is 2 bytes wide like 01C5 (as string). For my application, i have to swap high and low byte.

I tried it this way:

valueLow = hex(int(value,16) >> 8)
valueHigh = hex(int(value,16) & 0x0011)

but the results I get are now what they should look like.

Do you have a better solution?

Creatronik
  • 189
  • 3
  • 18

1 Answers1

0

Use this to get the byte-swapped value:

swappedValue = hex(value<<8&0xff00 | value>>8&0x00ff)

or, if value is a string,

swappedValue = hex(int(value,16)<<8&0xff00 |int(value,16)>>8&0x00ff)

If you need a number (for I2C), try:

swappedValue = int(value,16)<<8&0xff00 | int(value,16)>>8&0x00ff
FinalState
  • 91
  • 1
  • 4
  • Thanks that looks very elegant. But as "value" is a string it generates this message: TypeError: unsupported operand type(s) for <<: 'str' and 'int' Unfortunately applying "hex()" to "value" does also generate an error: TypeError: hex() argument can't be converted to hex – Creatronik Jun 02 '15 at 13:45