How do you combine two bytes in python?

安稳与你 提交于 2019-12-08 13:57:38

问题


Say you have b'\x04' and b'\x00' how can you combine them as b'\x0400'?


回答1:


Using python 3:

>>> a = b'\x04'
>>> b = b'\x00'
>>> a+b
b'\x04\x00'



回答2:


0x01 << 8 = 0x0100
0X0100 | 0X01 = 0X0101

You can use this two operation.

<< 8 for shift 8 bit or one byte

| for merging.

a = b'0x04'
a << 8
b'0x0400'



回答3:


It has a simple solution like this: 0x0400 = 0x04 × 256 + 0x00




回答4:


In my application I am receiving a stream of bytes from a sensor. I need to combine two of the bytes to create the integer value.

Hossein's answer is the correct solution.

The solution is the same as when one needs to bit shift binary numbers to combine them for instance if we have two words which make a byte, high word 0010 and low word 0100. We can't just add them together but if we bit shift the high word to the left four spaces we can then or the bits together to create 00100100. By bit shifting the high word we have essencially multiplied it by 16 or 10000.

In hex example above we need to shift the high byte over two digits which in hex 0x100 is equal to 256. Therefore, we can multiple the high byte by 256 and add the low byte.



来源:https://stackoverflow.com/questions/43168123/how-do-you-combine-two-bytes-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!