Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise operator to get byte from 32 bits

I am interested in writing a function getMyByteChunkFunction that accepts two parameters - a 32-bit integer and a byte offset (0, 1, 2, or 3), then returns the corresponding byte out of the 32-bit integer. For example, given this integer:

            (3)         (2)      (1)      (0)   ---byte numbers
int word = 10101010 00001001 11001010 00000101

the function call getMeByteChunkFunction(word, 2) returns 00001001.

However, I am limited in the bitwise operators I can use. I am only allowed to use >>, <<, and exactly one subtraction. I know how to do this using AND and XOR, but I don't know how I'd use a subtraction here. Any ideas?

like image 432
David Avatar asked Sep 01 '11 23:09

David


People also ask

What is bitwise ANDing?

Bitwise ANDing is frequently used for masking operations. That is, this operator can be used easily to set specific bits of a data item to 0. For example, the statement. w3 = w1 & 3; assigns to w3 the value of w1 bitwise ANDed with the constant 3.

What is the result of 0110 & 1100?

4) What is the result of 0110 & 1100.? Explanation: Bitwise & operator gives 1 if both operands are 1. 1&1 = 1.

What is Bitwise operator used to set a particular bit value to 1?

The bitwise-inclusive-OR operator compares each bit of its first operand to the corresponding bit of its second operand. If either bit is 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.


1 Answers

One idea is as follows. Suppose that you have a four-byte value like this one:

aaaaaaaa bbbbbbbb cccccccc dddddddd

Let's suppose that you want to get the byte bbbbbbbb out of this. If you shift right by two bytes, you get

???????? ???????? aaaaaaaa bbbbbbbb

This value is equal to what you want, except that at the top it has ???????? ???????? aaaaaaaa (because we're not sure if the shift is sign-preserving or not, since I don't know if your value is unsigned or not.) No worries, though; we can get rid of these unknown values and the a byte. To get rid of the top, suppose that you shift right another byte, giving

???????? ???????? ???????? aaaaaaaa

Now, shift left one byte to get

???????? ???????? aaaaaaaa 00000000

If you then do this subtraction, you get

    ???????? ???????? aaaaaaaa bbbbbbbb
-   ???????? ???????? aaaaaaaa 00000000
---------------------------------------
    00000000 00000000 00000000 bbbbbbbb

And voilà... you've got the value you want!

I'll leave the actual code as an exercise to the reader. Don't worry; it's not particularly hard. :-)

like image 88
templatetypedef Avatar answered Oct 20 '22 14:10

templatetypedef