8

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

0

5 Answers 5

21

Using python 3:

>>> a = b'\x04'
>>> b = b'\x00'
>>> a+b
b'\x04\x00'
Sign up to request clarification or add additional context in comments.

Comments

8
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'

Comments

5

Another alternative in Python3 is:

b''.join([a,b])

If you have the byte elements in list say bytes_list, you can treat as normal list join.

b''.join(bytes_list)

Comments

0

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.

Comments

-1

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

3 Comments

You can describe your answer to be more useful.
Yes.every byte is at much 255 in dec and if you want merge two byte you can do as i did. Another way is using "<<" for shift byte to left and using "|" to merge like: " 0x04 << 8 " shit 8 bit or 1 byte
Please edit your answer and append the comment. As any detail in the comments is not useful as the answer.

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.