Please take a look at my function:
int getByte(int x, int n) {
int oneOnes = 255 << ( n << 3);
int compute = oneOnes & x;
//FIND A WAY TO RETURN CHAR (NOT INT)
char result = (compute >> (n << 3));
return result;
}
Everthing works great until the comment. That is, I start with an integer x, and I want to take only a certain subsection (specified by n). So what I did was make everything except the 8 bits I want to keep into zeros. So for example, if the input was:
1001011 10011011 00101011 01001011
And I want to keep only the 3rd group of bits (counting from the right), then the result would be:
00000000 10011011 00000000 00000000
So I’ve managed to do that correctly. The issue is, I need to return only the bits that I want (with the zeros cropped, as a char). Despite creating a char result and returning that, what’s being returned is still the 32 bit value.
Any help? Thanks!
To be clear: For 00000000 10011011 00000000 00000000, I want only 10011011 to be returned.
Thanks!
The basic problem is that you’re trying to use signed integers to do this, but shifts of signed integers are not well defined — whenever the bit pattern happens to be a negative value, bad things happen.
Instead, as is usually the case when doing bit manipulations, you want to use unsigned integers:
Its even easier if you do the masking AFTER the shifting, as then you don’t need to shift the mask: