Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set multiple bits in one line in C?

I'd write two lines to set, say, some bits to something. Here, for example, I want to set upper 8 bits in uint16_t value x to y's lower 8 bits.

uint16_t y = 0x0034;
uint16_t x = 0xFF12;

I want to have x:

assert(x == 0x3412);

I tend to write these two lines:

x &= 0x00FF;
x |= (y << 8);

Is there a way of writing a single line to achieve the same effect without using macro?

like image 737
Sangcheol Choi Avatar asked Feb 14 '14 18:02

Sangcheol Choi


People also ask

How to set a single bit in C/C++?

How to set, clear or toggle a single bit in C/C++? Bitwise Operators are mainly used in low-level programming. Using the bit-wise operators we can set bit, check bit, clear or toggle the bits of an integral type. In the embedded system, a bit-wise operator performs the bit-wise operation on an individual bit of a PORT or Register.

How do you set a bit in a set bit?

Any bit <bitwise OR> Set bit = Set bit which means, 0 | 1 = 1 1 | 1 = 1 So for setting a bit, performing a bitwise OR of the number with a set bit is the best idea. N = N | 1 << K OR N |= 1 << K where K is the bit that is to be set

How to toggle and clear a bit in C?

Set, toggle and clear a bit in C 1 Setting a bit. Use the bitwise OR operator ( |) to set a bit. That will set a bit x. 2 Clearing a bit. Use the bitwise AND operator ( &) to clear a bit. That will clear bit x. ... 3 Toggling a bit. The XOR operator ( ^) can be used to toggle a bit. That will toggle bit x. That’s it, hope it helps.

What is bitwise OR operator | in C?

In C, bitwise OR operator ( |) used to set a bit of integral data type. As we know that | (Bitwise OR operator) evaluates a new integral value in which each bit position is 1 only when operand’s (integer type) has a 1 in that position.


1 Answers

Just expand out the two lines:

x &= 0x00FF; // x = x & 0xFF
x |= (y<<8); // x = x | (y<<8)

// and combine

x = (x & 0xFF) | (y << 8);
like image 152
clcto Avatar answered Sep 25 '22 02:09

clcto