Unset the far right bit in a byte - bit-manipulation

How can I unset the far right set bit in the most efficient way.
For example:
For 12 (dec) = 00001100 (bin)
I want to get: 8(dec) = 00001000 (bin)

Never mind, I guess the following is the most efficient way of doing it:
i = (i - 1) & i

Related

How do I make a bit mask that only masks certain parts (indices) of 32 bits?

I am currently working on a programming assignment in which I have to mask only a certain index of the whole 32-bit number(EX: If I take 8 4-bit numbers into my 32-bit integer, I would have 8 indices with 4 bits in each). I want to be able to print only part of the bits out of the whole 32 bits, which can be done with masking. If the bits were to only be in one place, I would not have a problem, for I would just create a mask that puts the 1s in a set place(EX: 00000000 00000000 00000000 00000001). However, I need to be able to shift the mask throughout only one index to print each bit (EX: I want to loop through the first index with my 0001 mask, shifting the 1 left every time, but I do not want to continue after the third bit of that index). I know that I need a loop to accomplish this; however, I am having a difficult time wrapping my head around how to complete this part of my assignment. Any tips, suggestions, or corrections would be appreciated. Also, I'm sorry if this was difficult to understand, but I could not find a better way to word it. Thanks.
first of all about representation. You need binary numbers to represent bits and masks. There are no binaries implemented directly in c/c++ languages at least before c++14. So, before c++14 you had to use hexadecimals or octals to represent your binaries, i.e.
0000 1111 == 0x0F
1111 1010 == 0xFA
since c++14 you can use
0b00001111;
Now, if you shift your binary mask left or right, you will have the following pictures
00001111 (OxF) << 2 ==> 00111100 (0x3C)
00001111 (0xF) >> 2 ==> 00000011 (0x03)
Now, supposedly you have an number in which you are interested in bits 4 to 7 (4 bits)
int bad = 0x0BAD; // == 0000 1011 1010 1101
you can create a mask as
int mask = 0x00F0; // == 0000 0000 1111 00000
and do bitwise and
int result = bad & mask; // ==> 0000 0000 1010 000 (0x00A0)
You will mask 4 bits in the middle of the word, but it will print as 0xA0. probably not what you would expect. To print it as 0xA you would need to shift the result 4 bits right: result >> 4. I prefer doing it in a bit different order, shifting the 'bad' first and then mask:
int result = (bad >> 4) & 0xF;
I hope the above will help you to understand bits.

C++ Read 1 Bit From Memory?

So looking in debugger I have found that i need to check if 1 bit is set to a certain value.
For example lets say at this memory address 0x12345 holds these four bytes 01008100, how would I go about checking if ONLY 8 is right there in that exact point? Sorry I am at a lack of words to use, I am not even sure how to really explain. But for example if I wanted to check if 8 was right there in that exact position in those bytes posted above my first guess would be to try something like this
if(*(char*)(0x12345 + 0x2) == 8)
{
//ok
}
But this obivously won't work because it will read the value as 0x81, I need to ONLY read if the 8 is there and ignore all other bits in front or behind it. Hopefully this question was worded in a way that at least someone will understand my question. Thank you for reading have a good day.
You can use a bitwise AND (&) to test individual bits, e.g.
if ((*(char*)(0x12345 + 0x2) & 0x80) == 0x80)
{
//ok
}
Note that the AND operation masks out the bits you are not interested in, e.g.
0x12345 + 0x2: 10000001 ; 0x81
AND with 0x80: 10000000 ; 0x80
It looks like you want to check if a particular bit in your 4 bytes value is set or not.
Assuming that you want to check the bit on a stream of bytes, and NOT on a 32 bits value, then I would use something similar to what you specified, but I would use a bitwise and operator:
if((*(std::uint8_t*)(0x12345 + 0x2) & 0x80) != 0)
{
// the bit is set
}
If you are trying to check the bit in a uint32 value, then you have to consider the endianness of the machine you are working with (high or low bit endian).
Fortunately, if you specify the right data type then the machine will take care of that for you.
// Note: 0x12345 is a fictional address, not properly aligned on some architectures
if((*(std::uint32_t*)0x12345 & 0x00008000) != 0)
{
// the bit is set
}

Finding the dominating bit

I'm trying to determine if a bitstring, say 64 bit long, is at least 50% ones. I've searched around and looked at the great http://graphics.stanford.edu/~seander/bithacks.html, but I haven't found anything specifically for this problem.
I can split the string up into 8bit chunks, pre-calculate the number of 1s in each, and then find the result in 8 lookups and 7 additions.
Example of bytewise approach:
10001000 10000010 00111001 00001111 01011010 11001100 00001111 11110111
2 + 2 + 4 + 4 + 4 + 4 + 4 + 7 = 31
hence 0 dominates.
I just feel like there must be a better way given I just want to find the dominator. Maybe I'm just using the wrong name?
You can use the divide and concur solution here, which is easy adaptable to 32-bit. Or maybe just a popcnt instruction depending on your hardware. Then you just check if that value is less than 32, if so 0s dominate, otherwise 1s dominate.
The code from the link adapted to 64-bit and with the domination logic inserted:
(I've bit shifted right by an extra 5 bits at the end to check if the set bits is greater than 31 in the same shift)
int AtLeastHalfOnes(long long i) {
i = i - ((i >> 1) & 0x5555555555555555LL);
i = (i & 0x3333333333333333LL) + ((i >> 2) & 0x3333333333333333LL);
return (((i + (i >> 4)) & 0x0F0F0F0F0F0F0F0FLL) * 0x0101010101010101LL) >> 61;
}
I think it is better to use Stack data structure. When your input bit is 1, then push(1);. Otherwise pop(); from top of your stack. Finally if your stack is not empty, I think your problem solved.

Convert one-hot encoding to plain binary

This isn't a regular "binary to bcd" question, in fact, I'm not really sure what to call the thing I'm trying to do!
There is a single byte in an embedded device that stores the numbers 1 through 7 (for days of the week) in the following format:
00000001 = 1
00000010 = 2
00000100 = 3
00001000 = 4
00010000 = 5
00100000 = 6
01000000 = 7
I want to read this byte, and convert its contents (1 through 7) into BCD, but I'm not sure how to do this.
I know I could just brute-force it with a series of if statements:
if(byte == B00000001)
{
answer = 1;
}
else
if(byte == B00000010)
{
answer = 2;
}
and so on, but I think there could be a better way. This data is stored in a single register on a real time clock. I'm getting this byte by performing an I2C read, and I read it into a byte in my program. The datasheet for this real-time clock specifies that this particular register is formatted as I have outlined above.
You can use a lookup table...
/* this is only needed once, if lut is global or static */
unsigned char lut[65];
lut[1]=1;
lut[2]=2;
lut[4]=3;
lut[8]=4;
lut[16]=5;
lut[32]=6;
lut[64]=7;
...
...
...
/* Perform the conversion */
answer = lut[byte];
Or you can even use some math...
answer = 1 + log(byte)/log(2);
If this is being compiled on an ARM processor, you can simply do this:
result = 31 - __CLZ(number);
Assuming number is a 32-bit one-hot > 0.
You can make use of bitwise and modulo operations to do this efficiently without needing to create a large array
for (int answer = 1; (byte % 2) == 0; ++answer) {
byte >>= 1;
}
(I know this was an old question, I just wanted to share because this was a high Google result for me)

Are bitwise operations going to help me to serialize some bools?

I'm not used to binary files, and I'm trying to get the hang of it. I managed to store some integers and unsigned char, and read them without too much pain. Now, when I'm trying to save some booleans, I see that each of my bool takes exactly 1 octet in my file, which seems logical since a lone bool is stored in a char-sized data (correct me if I'm wrong!).
But since I'm going to have 3 or 4 bools to serialize, I figure it is a waste to store them like this : 00000001 00000001 00000000, for instance, when I could have 00000110. I guess to obtain this I should use bitwise operation, but I'm not very good with them... so could somebody tell me:
How to store up to 8 bools in a single octet using bitwise manipulations?
How to give proper values to (up to 8 bools) from a single octet using bitwise manipulation?
(And, bonus question, does anybody can recommend a simple, non-mathematical-oriented-mind like mine, bit manipulation tutorial if this exists? Everything I found I understood but could not put into practice...)
I'm using C++ but I guess most C-syntaxic languages will use the same kind of operation.
To store bools in a byte:
bool flag; // value to store
unsigned char b = 0; // all false
int position; // ranges from 0..7
b = b | (flag << position);
To read it back:
flag = (b & (1 << position));
The easy way is to use std::bitset which allows you to use indexing to access individual bits (bools), then get the resulting value as an integer. It also allows the reverse.
int main() {
std::bitset<8> s;
s[1] = s[2] = true; // 0b_0000_0110
cout << s.to_ulong() << '\n';
}
Without wrapping in fancy template/pre-processor machinery:
Set bit 3 in var:var |= (1 << 3)
Set bit n in var:var |= (1 << n)
Clear bit n in var:var &= ~(1 << n)
Test bit n in var: (the !! ensures the result is 0 or 1)!!(var & (1 << n))
Try reading this in order.
http://www.cprogramming.com/tutorial/bitwise_operators.html
http://www-graphics.stanford.edu/~seander/bithacks.html#ConditionalSetOrClearBitsWithoutBranching
Some people willthink that 2nd link is way too hardcore, but once you will master simple manipulation, it will come handy.
Basic stuff first:
The only combination of bits that means false is 00000000 all the others mean true i.e: 00001000,01010101
00000000 = 0(decimal), 00000001 = 2^0, 00000010 = 2^1, 00000100 = 2^2, …. ,10000000 = 2^7
There is a big difference between the operands (&&, ||) and (&,|) the first ones give the result of the logic operation between the two numbers, for example:
00000000 && 00000000 = false,
01010101 && 10101010 = true
00001100 || 00000000 = true,
00000000 || 00000000 = false
The second pair makes a bitwise operation (the logic operation between each bit of the numbers):
00000000 & 00000000 = 00000000 = false
00001111 & 11110000 = 00000000 = false
01010101 & 10101001 = 00000001 = true
00001111 | 11110000 = 11111111 = true
00001100 | 00000011 = 00001111 = true
To work with this and play with the bits, you only need to know some basic tricks:
To set a bit to 1 you make the operation | with an octet that has a 1 in that position and ceros in the rest.
For example: we want the first bit of the octet A to be 1 we make: A|00000001
To set a bit to 0 you make the operation & with an octet that has a 0 in that position and ones in the rest.
For example: we want the last bit of the octet A to be 0 we make: A&01111111
To get the Boolean value that holds a bit you make the operation & with an octet that has a 1 in that position and ceros in the rest.
For example: we want to see the value of the third bit of the octet A, we make: A&00000100, if A was XXXXX1XX we get 00000100 = true and if A was XXXXX0XX we get 00000000 = false;
You can always serialize bitfields. Something like:
struct bools
{
bool a:1;
bool b:1;
bool c:1;
bool d:1;
};
has a sizeof 1