Bitshifting and making sure the last two digits are 10 in C - c

How do I bitshift so I only need to compare the first two digits in a number? Say I want to compare 10101011010 the last two bits and make sure it's 10.
How would I do that?

If you want to check if certain bits are set in an integer, you'd use the binary and operator (&) and a mask. In the mask you set the bits you want to check and then use this mask to separate the bits you want to check.
So in your example:
val = b10101011010
And you want to make sure the last 2 bits are 10:
y = b10 = 0x02 = 2
than you make the mask so it selects the last 2 bits:
mask = b00000000011 = 0x03 = 3 (I'd use the hex notation to make it more clear)
or you could use bitshifting:
mask = (0x01 << 0) | (0x01 << 1) (setting bit 0 and bit 1 and oring them together)
Now we use the binary and operator:
val = b10101011010
mask = b00000000011
& -----------------
res = b00000000010
--> now we have our bits we are interested in
and we compare res with the value you want them to be:
if (res == y)
// -> good
else
// -> bad

Related

Retrieve specific bit from a bit mask [duplicate]

I don't quite understand this whole bitmask concept.
Let's say I have a mask:
var bitMask = 8 | 524288;
I undestand that this is how I would combine 8 and 524288, and get 524296.
BUT, how do I go the other way? How do I check my bitmask, to see if it contains 8 and/or 524288?
To make it a bit more complex, let's say the bitmask I have is 18358536 and I need to check if 8 and 524288 are in that bitmask. How on earth would I do that?
well
if (8 & bitmask == 8 ) {
}
will check if the bitmask contains 8.
more complex
int mask = 8 | 12345;
if (mask & bitmask == mask) {
//true if, and only if, bitmask contains 8 | 12345
}
if (mask & bitmask != 0) {
//true if bitmask contains 8 or 12345 or (8 | 12345)
}
may be interested by enum and more particularly FlagsAttibute.
I'm pretty sure (A & B)==B where A is the bitmask and B is whatever you want to check should do.
Example:
if((18358536 & 8) == 8)
{
// mask contains 8
}
First of all, bitmasks are for operating on bits, not integers. It is much easier to understand when we deal with just 1's and 0's than more complex numbers.
So for example:
1000110000010000100001000 = 18358536 // in binary.
0000010000000000000000000 = 524288 // in binary.
0000000000000000000001000 = 8 // in binary.
0000010000000000000001000 = 524296 // in binary.
With this, it is clear that integer 8 is a 4th bit from the right side and no other bits marked, so when we add 8 to 524288 (20th bit only) we are simply marking 4th and 20th bits as being true. So we can use the same space in memory reserved for an integer to hold multiple flags that define some boolean properties.
As Alex already explained, you can then check if any flag is available in bitmask by using bitwise AND operator:
if ((mask & flag) == flag) { /* mask has flag set as true */ }
You can read everything about bitmasks in this article

How do I set a new bit pattern in a certain position without changing the rest of the bits in C?

Suppose I have the following unsigned long val = 0xfedcba9876543210 and I want to change the 16 least significant bits to 0xabcd. So, the original value will be changed to unsigned long val = 0xfedcba987654abcd. I already have a function get that can return 0x3210, but I'm unsure how I can change this section of the value to 0xabcd. For more context, here is what I am trying to implement:
void set_pattern(unsigned long* val, int i, unsigned short new_pattern) {
// my attempt
unsigned short old_pattern = get(val, i); // ex: returns 0x3210 when i = 0
unsigned short* ptr = NULL;
ptr = &old_pattern;
*ptr = new_pattern;
}
When I tried my attempt, it seemed to not set the new pattern as I expected. Any help or feedback is appreciated in helping me gain a better understanding of C.
To explain Nate's comment, you want to apply a bitmask to zero out the relevant bits, then apply the new bits with a bitwise or.
Let's do it with 32 bits and you want to change the the least 8.
Apply a bitmask to turn the least 8 bits to 0. val = val & ~0xff. ~0xff is 0xffffff00. Since 0 & x = 0, all the filled in bits will retain their value, and all the 0's will become 0 no matter their original value.
0x12345678 val
AND 0xffffff00 ~0xff
= 0x12345600
Now that the relevant bits have been masked out, turned to 0, we can overwrite just them with a bitwise or. val = val | new_value. x | 0 = x. The irrelevant bits of new_value are 0. x | 0 = x. They will retain val's value. The relevant bits of val are 0. 0 | x = x. They will retain new_value's value.
0x12345600 val
OR 0x000000ef new_value
= 0x123456ef
If you want to replace different bits, you need to shift the bitmask and replacement value the appropriate amount.
Let's say we want to replace 56 with ef instead. Each hex character is 4 bits, so we need to left shift both the bitmask and replacement value by 8 bits.
0x12345678 val
AND 0xffff00ff ~(0xff << 8) == ~0xff00
= 0x12340078
0x12340078 val
OR 0x0000ef00 new_value << 8 == 0xef00
= 0x1234ef78
Well simple solution to it:
0xfedcba9876543210 & 0xfedcba9876540000
0xfedcba9876540000 | 0x000000000000abcd

Swapping bits in an integer in C, can you explain this function to me?

I want to write a function that receives an unsigned char and swaps between bit 2 and bit 4 and returns the new number.
I am not allowed to use if statement.
So I found this function, among other functions, but this was the most simple one to understand (or try to understand).
All other functions involve XOR which I don't really understand to be honest.
unsigned char SwapBits(unsigned char num)
{
unsigned char mask2 = ( num & 0x04 ) << 2;
unsigned char mask4 = ( num & 0x10 ) >> 2;
unsigned char mask = mask3 | mask5 ;
return ( num & 0xeb ) | mask;
}
Can someone explain me what happens here and most important, why?
Why AND is required here and why with hex address?
Why should I AND with 0xeb (255)? I know that's the range of char but why should I do that.
In short,
I know how to read codes. I understand this code, but I don't understand the purpose of each line.
Thanks.
First, the usual convention is that bits are numbered starting from 0 for the least significant bit and counting up. In this case, you have an 8-bit value, so the bits go from 0 on the right up to 7 on the left.
The function you posted still isn't quite right, but I think I see where you (it) was going with it. Here are the steps it's doing:
Pull out bit 2 (which is 3rd from the right) using a mask
Pull out bit 4 (which is 5th from the right) using a mask
Shift bit 2 left 2 positions so it's now in bit 4's original position
Shift bit 4 right 2 positions so it's now in bit 2's original position
Join these two bits together into one value that is now bits 2 and 4 swapped
Mask out (erase using &) only bits 2 and 4 from the original value
Join in (insert using |) the new swapped bits 2 and 4 to complete the transformation
I have rewritten the function to show each step one at a time to help make it clearer. In the original function or other examples you find, you'll see many of these steps all happen together in the same statement.
unsigned char SwapBits(unsigned char num)
{
// preserve only bit 2
unsigned char bit2 = num & 0x04;
// preserve only bit 4
unsigned char bit4 = num & 0x10;
// move bit 2 left to bit 4 position
unsigned char bit2_moved = bit2 << 2;
// move bit 4 right to bit 2 position
unsigned char bit4_moved = bit4 >> 2;
// put the two moved bits together into one swapped value
unsigned char swapped_bits = bit2_moved | bit4_moved;
// clear bits 2 and 4 from the original value
unsigned char num_with_swapped_bits_cleared = num & ~0x14;
// put swapped bits back into the original value to complete the swap
return num_with_swapped_bits_cleared | swapped_bits;
}
The second to last step num & ~0x14 probably needs some explanation. Since we want to save all the original bits except for bits 2 and 4, we mask out (erase) only the bits we're changing and leave all the others alone. The bits we want to erase are in positions 2 and 4, which are the 1s in the mask 0x14. So we do a complement (~) on 0x14 to turn it into all 1s everywhere except for 0s in bits 2 and 4. Then we AND this value with the original number, which has the effect of changing bits 2 and 4 to 0 while leaving all the others alone. This allows us to OR in the new swapped bits as the final step to complete the process.
You have to read about binary representation of number
unsigned char SwapBits(unsigned char num)
{
// let say that [num] = 46, it means that is is represented 0b00101110
unsigned char mask2 = ( num & 0x04 ) << 2;
// now, another byte named mask2 will be equal to:
// 0b00101110 num
// 0b00000100 0x04
// . .1. mask2 = 4. Here the & failed with . as BOTH ([and]) bits need to be set. Basically it keeps only numbers that have the 3rd bit set
unsigned char mask4 = ( num & 0x10 ) >> 2;
// 0b00101110 num
// 0b00010000 0x10 -> means 16 in decimal or 0b10000 in binary or 2^4 (the power is also the number of trailing 0 after the bit set)
// 0b00.....0 mask4 = 0, all bits failed to be both set
unsigned char mask = mask3 | mask5 ;
// mask will take bits at each position if either set by mask3 [or] mask5 so:
// 0b1001 mask3
// 0boo11 mask4
// 0b1011 mask
return ( num & 0xeb ) | mask; // you now know how it works ;) solve this one. PS: operation between Brackets have priority
}
If you are interested to learn the basics of bitwise operators you can take a look at this introduction.
After you build confidence you can try solving algorithms using only bitwise operators, where you will explore even deeper bitwise operations and see its impact on the runtime ;)
I also recommend reading Bit Twiddling Hacks, Oldies but Goodies!
b = ((b * 0x80200802ULL) & 0x0884422110ULL) * 0x0101010101ULL >> 32; // reverse your byte!
Simple function to understand swap of bit 3 and 5:
if you want to swap bit index 3 and bit index 5, then you have to do the following:
int n = 0b100010
int mask = 0b100000 // keep bit index 5 (starting from index 0)
int mask2 = 0b1000 // keep bit index 3
n = (n & mask) >> 2 | (n & mask2) << 2 | (n & 0b010111);
// (n & mask) >> 2
// the mask index 5 is decrease by 2 position (>>2) and brings along with it the bit located at index 5 that it had captured in n thanks to the AND operand.
// | (n & mask2) << 2
// mask2 is increased by 2 index and set it to 0 since n didn't have a bit set at index 3 originally.
// | (n & 0b010111); // bits 0 1 2 and 4 are preserved
// since we assign the value to n all other bits would have been wiped out if we hadn't kept their original value thanks to the mask on which we do not perform any shift operations.

Changing more than one bit in a register

I have an 8 bit register and I want to change bits 4,5 and 6 without altering the other bits.
Those bit can take values from 000 to 111 (regardless their previous state).
Is there a method to change them in one step or must I change them individually?
You need a mask to put the requested bits in a known state, 0 is the more convenient as per my programming habits, then set the bits that you want to 1 with an or operation and write back:
#define mask 0x70 // 01110000b bit 4, 5 & 6 set
reg = (reg & ~mask) | (newVal & mask);
We use the inverted mask to set to 0 the bits to change and the unchanged mask to set to 0 the bits that we don't want to interfere from the new value.
If you are sure that the unwanted bits of the new value are always 0 you can simplify:
#define mask 0x8f // 10001111b bit 4, 5 & 6 reset
reg = (reg & mask) | newVal; //newVal must have always bits 7, 3, 2, 1 & 0 reset.
You can do it by bitwise operation, i.e. first clear the 3 bits, and then set them:
unsigned char value = 0x70;
unsigned char r = 0xFF;
r = (r & 0x8F) | value;
You can use bit-field inside a struct:
typedef struct{
unsigned char b0_3 : 4;
unsigned char b4_6 : 3;
unsigned char b7 : 1;
}your_reg_type;
your_reg_type my_register;
//modify only the bits you need
my_register.b4_6 = 0x02;
Check out how your compiler orders the bits inside the struct before trying and order your bit-field accordingly
A number of solutions and variations are possible (and have been suggested already), but if the value of the three consecutive bits has meaning in-itself (i.e. it is a value 0 to 7 rather then simply a collection of independent flag or control bits for example), it may be useful to keep the value as a simple numeric range 0 to 7 rather then directly encoding details of bit position within the value. In which case:
assert( val <= 7 ) ; // During debug (when NDEBUG not defined) the
// assert trap will catch out-of-range inputs
reg = (reg & mask) | (val << 4) ;
Of course there is some small cost to pay for simplifying the interface in this way (by adding a shift operation), but the advantage is that knowledge of the details of the register field layout is restricted to one place.

reading 2 bits off a register

I'm looking at a datasheet specification of a NIC and it says:
bits 2:3 of register contain the NIC speed, 4 contains link state, etc. How can I isolate these bits using bitwise?
For example, I've seen the code to isolate the link state which is something like:
(link_reg & (1 << 4))>>4
But I don't quite get why the right shift. I must say, I'm still not fairly comfortable with the bitwise ops, even though I understand how to convert to binary and what each operation does, but it doesn't ring as practical.
It depends on what you want to do with that bit. The link state, call it L is in a variable/register somewhere
43210
xxxxLxxxx
To isolate that bit you want to and it with a 1, a bitwise operation:
xxLxxxx
& 0010000
=========
00L0000
1<<4 = 1 with 4 zeros or 0b10000, the number you want to and with.
status&(1<<4)
This will give a result of either zero or 0b10000. You can do a boolean comparison to determine if it is false (zero) or true (not zero)
if(status&(1<<4))
{
//bit was on/one
}
else
{
//bit was off/zero
}
If you want to have the result be a 1 or zero, you need to shift the result to the ones column
(0b00L0000 >> 4) = 0b0000L
If the result of the and was zero then shifting still gives zero, if the result was 0b10000 then the shift right of 4 gives a 0b00001
so
(status&(1<<4))>>4 gives either a 1 or 0;
(xxxxLxxxx & (00001<<4))>>4 =
(xxxxLxxxx & (10000))>>4 =
(0000L0000) >> 4 =
0000L
Another way to do this using fewer operations is
(status>>4)&1;
xxxxLxxxx >> 4 = xxxxxxL
xxxxxxL & 00001 = 00000L
Easiest to look at some binary numbers.
Here's a possible register value, with the bit index underneath:
00111010
76543210
So, bit 4 is 1. How do we get just that bit? We construct a mask containing only that bit (which we can do by shifting a 1 into the right place, i.e. 1<<4), and use &:
00111010
& 00010000
----------
00010000
But we want a 0 or a 1. So, one way is to shift the result down: 00010000 >> 4 == 1. Another alternative is !!val, which turns 0 into 0 and nonzero into 1 (note that this only works for single bits, not a two-bit value like the link speed).
Now, if you want bits 3:2, you can use a mask with both of those bits set. You can write 3 << 2 to get 00001100 (since 3 has two bits set). Then we & with it:
00111010
& 00001100
----------
00001000
and shift down by 2 to get 10, the desired two bits. So, the statement to get the two-bit link speed would be (link_reg & (3<<2))>>2.
If you want to treat bits 2 and 3 (starting the count at 0) as a number, you can do this:
unsigned int n = (link_get & 0xF) >> 2;
The bitwise and with 15 (which is 0b1111 in binary) sets all but the bottom four bits to zero, and the following right-shift by 2 gets you the number in bits 2 and 3.
you can use this to determine if the bit at position pos is set in val:
#define CHECK_BIT(val, pos) ((val) & (1U<<(pos)))
if (CHECK_BIT(reg, 4)) {
/* bit 4 is set */
}
the bitwise and operator (&) sets each bit in the result to 1 if both operands have the corresponding bit set to 1. otherwise, the result bit is 0.
The problem is that isolating bits is not enough: you need to shift them to get the correct size order of the value.
In your example you have bit 2 and 3 for the size (I'm assuming that least significant is bit 0), it means that it is a value in range [0,3]. Now you can mask these bits with reg & (0x03<<2) or, converted, (reg & 0x12) but this is not enough:
reg 0110 1010 &
0x12 0000 1100
---------------
0x08 0000 1000
As you can see the result is 1000b which is 8, which is over the range. To solve this you need to shift back the result so that the least significant bit of the value you are interested in corresponds to the least significant bit of the containing byte:
0000 1000 >> 2 = 10b = 3
which now is correct.

Resources