Bit Shifting & Manipulation - c

I'm trying to work with bit manipulation, and am struggling modifying the bits directly.
I have something as follows:
unsigned char myBits = 128; // 10000000 in binary
myBits = myBits >> 1; // Right shift, so we get 64, or 01000000 in binary
Now, how would I use bit manipulation to modify the first bit after the right shift (01000000) to a 1 (11000000)?

Most implementations will shift a "1" bit in from the left if the type in question is signed and the value is negative.
So you could either change the type to signed char, or do some casting on the unsigned types:
myBits = (unsigned char)((signed char)myBits >> 1);

you need to binary OR it with the shifted value:
myBits |= myBits >> 1;
https://godbolt.org/z/dY3eY5dc5
To set the most significant bit (you can change the type to any integer type and it will work):
myBits |= 1ULL << (sizeof(myBits) * CHAR_BIT - 1);

Related

In C, how to set first eight bits of any sized int in a generic way

How do I set the first (least significant) eight bits of any integer type to all zeroes? Essentially do a bitwise AND of any integer type with 0x00.
What I need is a generic solution that works on any integer size, but not have to create a mask setting all the higher bits to 1.
In other words:
0xffff & 0x00 = 0xff00
0xaabbccddeeffffff & 0x00 = 0xaabbccddeeffff00
With bit shifts:
any_unsigned_integer = any_unsigned_integer >> 8 << 8;
The simplest solution works for all integer types on architectures with 2's complement representation for negative numbers:
val = val & ~0xff;
The reason is ~0xff evaluates to -256 with type int. Let's consider all possible types for val:
if the type of val is smaller than int, val is promoted to int, the mask operation works as expected and the result is converted back to the type of val.
if the type of val is signed, -256 is converted to type of val preserving its value, hence replicating the sign bit, and the mask is performed properly.
If the type of val is unsigned, converting -256 to this type produces the value TYPE_MAX + 1 - 256 that has all bits set except the 8 low bits, again the proper mask for the operation.
Another simple solution, that works for all representations of negative values is this:
val = val ^ (val & 0xff);
It requires storing the value into a variable to avoid multiple evaluation, whereas the first proposal can be applied to any expression with potential side-effects:
return my_function(a, b, c) & ~0xff;
The C not operator ~ will invert all the bits of a given value so, in order to get a mask that will clear only the lower eight bits:
int val = 123456789;
int other_val = val & ~0xff; // AND with binary 1111 ... 1111 0000 0000
val &= ~0xff; // alternative to change original variable.
If you have a wider (or thinner) type, the 0xff should be of the correct type, for example:
long val = 123456789L;
long other_val = val & ~(long)0xff;
val &= ~(long)0xff; // alternative to change original variable.
One way to do it without a creating a mask for the higher bits is to use a combination of the & and ^ operators: x = x ^ (x & 0xFF); (or, using compound assignment: x ^= x & 0xFF;).
Universal solution no mask, any number of bits
#define RESETB(val, nbits) ((val) ^ ((val) & ((1ULL << (nbits)) - 1)))
or even better
#define RESETB(val, nbits) ((val) ^ ((val) & ((nbits) ? ((nbits) >= sizeof(val) * CHAR_BIT ? ((1ULL << (sizeof(val) * CHAR_BIT)) - 1) : ((1ULL << (nbits)) - 1)) : 0)))

How to get the most significant bit of an unsigned 8-bit type in C

I'm trying to get the most significant bit of an unsigned 8-bit type in C.
This is what I'm trying to do right now:
uint8_t *var = ...;
...
(*var >> 6) & 1
Is this right? If it's not, what would be?
To get the most significant bit from a memory pointed to by uint8_t pointer, you need to shift by 7 bits.
(*var >> 7) & 1
The most standard/correct way of masking bits is to use a readable bit mask of the form 1u << bit. Any C programmer spotting 1u << n in code will know that it is a bit mask - so it is self-documenting code.
So if you want bit number 7, you would write
*var & (1u << 7)
The u suffix is important for rugged code, since you want to avoid accidental implicit promotions to signed types.
Another option is to simply apply a bit mask and check the resulting value:
*var & 0x80u // 1000 0000

C - three bytes into one signed int

I have a sensor which gives its output in three bytes. I read it like this:
unsigned char byte0,byte1,byte2;
byte0=readRegister(0x25);
byte1=readRegister(0x26);
byte2=readRegister(0x27);
Now I want these three bytes merged into one number:
int value;
value=byte0 + (byte1 << 8) + (byte2 << 16);
it gives me values from 0 to 16,777,215 but I'm expecting values from -8,388,608 to 8,388,607. I though that int was already signed by its implementation. Even if I try define it like signed int value; it still gives me only positive numbers. So I guess my question is how to convert int to its two's complement?
Thanks!
What you need to perform is called sign extension. You have 24 significant bits but want 32 significant bits (note that you assume int to be 32-bit wide, which is not always true; you'd better use type int32_t defined in stdint.h). Missing 8 top bits should be either all zeroes for positive values or all ones for negative. It is defined by the most significant bit of the 24 bit value.
int32_t value;
uint8_t extension = byte2 & 0x80 ? 0xff:00; /* checks bit 7 */
value = (int32_t)byte0 | ((int32_t)byte1 << 8) | ((int32_t)byte2 << 16) | ((int32_t)extension << 24);
EDIT: Note that you cannot shift an 8 bit value by 8 or more bits, it is undefined behavior. You'll have to cast it to a wider type first.
#include <stdint.h>
uint8_t byte0,byte1,byte2;
int32_t answer;
// assuming reg 0x25 is the signed MSB of the number
// but you need to read unsigned for some reason
byte0=readRegister(0x25);
byte1=readRegister(0x26);
byte2=readRegister(0x27);
// so the trick is you need to get the byte to sign extend to 32 bits
// so force it signed then cast it up
answer = (int32_t)((int8_t)byte0); // this should sign extend the number
answer <<= 8;
answer |= (int32_t)byte1; // this should just make 8 bit field, not extended
answer <<= 8;
answer |= (int32_t)byte2;
This should also work
answer = (((int32_t)((int8_t)byte0))<<16) + (((int32_t)byte1)<< 8) + byte2;
I may be overly aggressive with parentheses but I never trust myself with shift operators :)

Getting four bits from the right only in a byte using bit shift operations

I wanted to try to get only the four bits from the right in a byte by using only bit shift operations but it sometimes worked and sometimes not, but I don't understand why.
Here's an example:
unsigned char b = foo; //say foo is 1000 1010
unsigned char temp=0u;
temp |= ((b << 4) >> 4);//I want this to be 00001010
PS: I know I can use a mask=F and do temp =(mask&=b).
Shift operator only only works on integral types. Using << causes implicit integral promotion, type casting b to an int and "protecting" the higher bits.
To solve, use temp = ((unsigned char)(b << 4)) >> 4;

Signed right shift = strange result?

I was helping someone with their homework and ran into this strange issue. The problem is to write a function that reverses the order of bytes of a signed integer(That's how the function was specified anyway), and this is the solution I came up with:
int reverse(int x)
{
int reversed = 0;
reversed = (x & (0xFF << 24)) >> 24;
reversed |= (x & (0xFF << 16)) >> 8;
reversed |= (x & (0xFF << 8)) << 8;
reversed |= (x & 0xFF) << 24;
return reversed;
}
If you pass 0xFF000000 to this function, the first assignment will result in 0xFFFFFFFF. I don't really understand what is going on, but I know it has something to do with conversions back and forth between signed and unsigned, or something like that.
If I either append ul to 0xFF it works fine, which I assume is because it's forced to unsigned then converted to signed or something in that direction. The resulting code also changes; without the ul specifier it uses sar(shift arithmetic right), but as unsigned it uses shr as intended.
I would really appreciate it if someone could shed some light on this for me. I'm supposed to know this stuff, and I thought I did, but I'm really not sure what's going on here.
Thanks in advance!
Since x is a signed quantity, the result of (x & (0xFF << 24)) is 0xFF000000 which is also signed and thus a negative number since the top (sign) bit is set. The >> operator on int (a signed value) performs sign extension (Edit: though this behaviour is undefined and implementation-specific) and propagates the sign bit value of 1 as the value is shifted to the right.
You should rewrite the function as follows to work exclusively on unsigned values:
unsigned reverse(unsigned x)
{
unsigned int reversed = 0;
reversed = (x & (0xFF << 24)) >> 24;
reversed |= (x & (0xFF << 16)) >> 8;
reversed |= (x & (0xFF << 8)) << 8;
reversed |= (x & 0xFF) << 24;
return reversed;
}
From your results we can deduce that you are on a 32-bit machine.
(x & (0xFF << 24)) >> 24
In this expression 0xFF is an int, so 0xFF << 24 is also an int, as is x.
When you perform the bitwise & between two int, the result is also an int and in this case the value is 0xFF000000 which on a 32-bit machine means that the sign bit is set, so you have a negative number.
The result of performing a right-shift on an object of signed type with a negative value is implementation-defined. In your case, as sign-preserving arithmetic shift right is performed.
If you right-shift an unsigned type, then you would get the results that you were expecting for a byte reversal function. You could achieve this by making either operand of the bitwise & operand an unsigned type forcing conversion of both operands to the unsigned type. (This is true on any implementation where an signed int can't hold all the possible range of positive values of an unsigned int which is nearly all implementations.)
Right shift on signed types is implementation defined, in particular the compiler is free to do an arithmetic or logical shift as pleases. This is something you will not notice if the concrete value that you are treating is positive, but as soon as it is negative you may fall into a trap.
Just don't do it, this is not portable.
x is signed, so the highest bit is used for the sign. 0xFF000000 means "negative 0x7F000000". When you do the shift, the result is "sign extended": The binary digit that is added on the left to replace the former MSB that was shifted right, is always the same as the sign of value. So
0xFF000000 >> 1 == 0xFF800000
0xFF000000 >> 2 == 0xFFC00000
0xFF000000 >> 3 == 0xFFE00000
0xFF000000 >> 4 == 0xFFF00000
If the value being shifted is unsigned, or if the shift is toward the left, the new bit would be 0. It's only in right-shifts of signed values that sign-extension come into play.
If you want it to work the same on al platforms with both signed and unsigned integers, change
(x & (0xFF << 24)) >> 24
into
(x >> 24) & 0xFF
If this is java code you should use '>>>' which is an unsigned right shift, otherwise it will sign extend the value

Resources