-1

Assume I have a 1 source variable (int) which is 10 bits long. Let's call it src. I have 2 destination variables (int) which are 8 bits long namely byte1 and byte2.

       MSB               LSB 
src    0 1 2 3 4 5 6 7 8 9  --- bit numbers
       1 1 0 0 1 0 1 1 1 0  --- assigned bits
       value 814

What I would like to do is copy the first 8 bits from src to byte1 and the last 2 bits from src to the MSB of byte2 so byte1 and byte2 should contain the following:

       MSB           LSB 
byte1  0 1 2 3 4 5 6 7   --- bit numbers
       1 1 0 0 1 0 1 1
       value 203

I can do this with byte1 = src >> 2 which works perfectly as intended

       MSB           LSB 
byte2  0 1 2 3 4 5 6 7
       1 0 0 0 0 0 0 0
       value 128

Where I am stuck is with byte2. I have tried creating a mask for the last 2 bits and ANDing the source and mask together and then ORing the extracted bits.

1
  • 1
    Include the actual code you currently have for byte2 rather than words. And what is your actual result for byte2 . Commented Sep 17 at 11:28

3 Answers 3

3
byte1, byte2 = (src << 6).to_bytes(2)

Attempt This Online!

Sign up to request clarification or add additional context in comments.

Comments

2

You can do (src & 0b11) to get the last two bits of the src, then shift those two to using << 6, placing the bits at the MSB side.
Python has arbitrary precision, so, as far as I know, truncation doesn't matter. In other languages, it might also be good practice to explicitly truncate your result using & 0xFF.

Comments

2

Shifting right by 2 is correct for getting your byte1 value. You could also floor divide by 4.

For byte2, you can "mask" src using a bitwise AND to get the 2 least significant bits. Then shift left by 6 or multiply by 64 like this:

src = 814

assert src < 1024 # ensure no more than 10 bits in src

w = 8

print(f"{src=:0{w}b}")

byte1a = src >> 2 # right shift by 2
print(f"{byte1a=:0{w}b}")

byte1b = src // 4 # floor divide by 4
print(f"{byte1b=:0{w}b}")

byte2a = (src & 3) << 6 # left shift by 6
print(f"{byte2a=:0{w}b}")

byte2b = (src & 3) * 64 # multiply by 64
print(f"{byte2b=:0{w}b}")

Output:

src=1100101110
byte1a=11001011
byte1b=11001011
byte2a=10000000
byte2b=10000000

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.