Invert (flip) last n bits of a number with only bitwise operations - c++

Given a binary integer, how can I invert (flip) last n bits using only bitwise operations in c/c++?
For example:
// flip last 2 bits
0110 -> 0101
0011 -> 0000
1000 -> 1011

You can flip last n bits of your number with
#define flipBits(n,b) ((n)^((1u<<(b))-1))
for example flipBits(0x32, 4) will flip the last 4 bits and result will be 0x3d
this works because if you think how XOR works
0 ^ 0 => 0
1 ^ 0 => 1
bits aren't flipped
0 ^ 1 => 1
1 ^ 1 => 0
bits are flipped
(1<<b)-1
this part gets you the last n bits
for example, if b is 4 then 1<<4 is 0b10000 and if we remove 1 we get our mask which is 0b1111 then we can use this to xor with our number to get the desired output.
works for C and C++

Related

Understanding two's complement

I don't understand why an n-bit 2C system number can be extended to an (n+1)-bit 2C system number by making bit bn = bn−1, that is, extending to (n+1) bits by replicating the sign bit.
This works because of the way we calculate the value of a binary integer.
Working right to left, the sum of each bit_i * 2 ^ i,
where
i is the range 0 to n
n is the number of bits
Because each subsequent 0 bit will not increase the magnitude of the sum, it is the appropriate value to pad a smaller value into a wider bit field.
For example, using the number 5:
4 bit: 0101
5 bit: 00101
6 bit: 000101
7 bit 0000101
8 bit: 00000101
The opposite is true for negative numbers in a two's compliment system.
Remember you calculate two's compliment by first calculating the one's compliment and then adding 1.
Invert the value from the previous example to get -5:
4 bit: 0101 (invert)-> 1010 + 1 -> 1011
5 bit: 00101 (invert)-> 11010 + 1 -> 11011
6 bit: 000101 (invert)-> 111010 + 1 -> 111011
7 bit: 0000101 (invert)-> 1111010 + 1 -> 1111011
8 bit: 00000101 (invert)-> 11111010 + 1 -> 11111011

Convert an 8 bit data to 3 bit data

PROGRAMMING LANGUAGE: C
I've a 8 bit data with only 3 bit used, for example:
0110 0001
Where 0 indicate unused bit that are always set to 0 and 1 indicate bits that change.
I want to convert this 0110 0001 8 bit to 3 bit that indicate this 3 used bits.
For example
0110 0001 --> 111
0010 0001 --> 011
0000 0000 --> 000
0100 0001 --> 101
How I can do that with minimal operations?
You can achieve this with a couple of bitwise operations:
((a >> 4) & 6) | (a & 1)
Assuming you start from xYYx xxxY, where x is a bit you don't care about and Y a bit to keep:
left shift by 4 of a will result in xYYx, then masking with 6 (binary 110) will make sure only the second and third bit are retained, resulting in YY0 and preventing flipped x bits from messing up.
a & 1 selects the LSB, resulting in Y.
the two parts, YY0 and Y are combined using a | bitwise or, resulting in YYY.
Now you have the 3 bits you asked. But keep in mind that you can't address single bits, so it will still be byte-aligned as 00000YYY
You can get the k'th bit of n: (where n is 011000001)
(n & ( 1 << k )) >> k
(More details about that at StackOverflow)
so you use that to get bit 1,6 and 7 and just add those:
r=bit1+bit6*16+bit7*32

How does this implementation of bitset::count() work?

Here's the implementation of std::bitset::count with MSVC 2010:
size_t count() const
{ // count number of set bits
static char _Bitsperhex[] = "\0\1\1\2\1\2\2\3\1\2\2\3\2\3\3\4";
size_t _Val = 0;
for (int _Wpos = _Words; 0 <= _Wpos; --_Wpos)
for (_Ty _Wordval = _Array[_Wpos]; _Wordval != 0; _Wordval >>= 4)
_Val += _Bitsperhex[_Wordval & 0xF];
return (_Val);
}
Can someone explain to me how this is working? what's the trick with _Bitsperhex?
_Bitsperhex contains the number of set bits in a hexadecimal digit, indexed by the digit.
digit: 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111
value: 0 1 1 2 1 2 2 3 1 2 2 3 2 3 3 4
index: 0 1 2 3 4 5 6 7 8 9 A B C D E F
The function retrieves one digit at a time from the value it's working with by ANDing with 0xF (binary 1111), looks up the number of set bits in that digit, and sums them.
_Bitsperhex is a 16 element integer array that maps a number in [0..15] range to the number of 1 bits in the binary representation of that number. For example, _Bitsperhex[3] is equal to 2, which is the number of 1 bits in the binary representation of 3.
The rest is easy: each multi-bit word in internal array _Array is interpreted as a sequence of 4-bit values. Each 4-bit value is fed through the above _Bitsperhex table to count the bits.
It is a slightly different implementation of the lookup table-based method described here: http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetTable. At the link they use a table of 256 elements and split 32-bit words into four 8-bit values.

Can I set a sequence of bits without unsetting the previous values?

I've got a sequence of bits, say
0110 [1011] 1111
Let's say I want to set that myddle nybble to 0111 as the new value.
Using a positional masking approach with AND or OR, I seem to have no choice but to first unset the original value to 0000, because if I trying ANDing or ORing against that original value of 1011, I'm not going to come out with the desired result of 0111.
Is there another logical operator I should be using to get the desired effect? Or am I locked into 2 operations every time?
The result after kindly assistance was:
inline void foo(Clazz* parent, const Uint8& material, const bool& x, const bool& y, const bool& z)
{
Uint8 offset = x | (y << 1) | (z << 2); //(0-7)
Uint64 positionMask = 255 << offset * 8; //255 = length of each entry (8 bits), 8 = number of bits per material entry
Uint64 value = material << offset * 8;
parent->childType &= ~positionMask; //flip bits to clear given range.
parent->childType |= value;
}
...I'm sure this will see further improvement, but this is the (semi-)readable version.
If you happen to already know the current values of the bits, you can XOR:
0110 1011 1111
^ 0000 1100 0000
= 0110 0111 1111
(where the 1100 needs to be computed first as the XOR between the current bits and the desired bits).
This is, of course, still 2 operations. The difference is that you could precompute the first XOR in certain circumstances.
Other than this special case, there is no other way. You fundamentally need to represent 3 states: set to 1, set to 0, don't change. You can't do this with a single binary operand.
You may want to use bit fields (and perhaps unions if you want to be able to access your structure as a set of bit fields and as an int at the same time) , something along the lines of:
struct foo
{
unsigned int o1:4;
unsigned int o2:4;
unsigned int o3:4;
};
foo bar;
bar.o2 = 0b0111;
Not sure if it translates into more efficient machine code than your clear/set...
Well, there's an assembly instruction in MMIX for this:
SETL $1, 0x06BF ; 0110 1011 1111
SETL $2, 0x0070 ; 0000 0111 0000
SETL rM, 0x00F0 ; set mask register
MUX $1,$2,$1 ; result is 0110 0111 1111
But in C++ here's what you're probably thinking of as 'unsetting the previous value'.
int S = 0x6BF; // starting value: 0110 1011 1111
int M = 0x0F0; // value mask: 0000 1111 0000
int V = 0x070; // value: 0000 0111 0000
int N = (S&~M) | V; // new value: 0110 0111 1111
But since the intermediate result 0110 0000 1111 from (S&~M) is never stored in a variable anywhere I wouldn't really call it 'unsetting' anything. It's just a bitwise boolean expression. Any boolean expression with the same truth table will work. Here's another one:
N = ((S^V) & M) ^ A; // corresponds to Oli Charlesworth's answer
The related truth tables:
S M V (S& ~M) | V ((S^V) & M) ^ S
0 0 0 0 1 0 0 0 0
* 0 0 1 0 1 1 1 0 0
0 1 0 0 0 0 0 0 0
0 1 1 0 0 1 1 1 1
1 0 0 1 1 1 1 0 1
* 1 0 1 1 1 1 0 0 1
1 1 0 0 0 0 1 1 0
1 1 1 0 0 1 0 0 1
^ ^
|____________________|
The rows marked with '*' don't matter because they won't occur (a bit in V will never be set when the corresponding mask bit is not set). Except for those rows, the truth tables for the expressions are the same.

how to calculate bitwise OR using AND, XOR and shift?

The question seems pretty well formulated
I have a virtual machine which implements only AND, XOR, SHL and SHR, yet I have to do a "OR 0x01" operation.
First of all having a correct bitwise computation for the following two variables is sufficient, because they cover all combinations:
A=0101
B=0011
We want
0101
0011
A or B
0111
for xor we get
0101
0011
A xor B
0110
for and we get
0101
0011
A and B
0001
so if we connect them with an xor we are done.
(A xor B) xor (A and B)
I would just start with
a xor b = ((not a) and b) or (a and (not b))
and unleash some boolean algebra on that until it looks like
a or b = <expression using only and, xor>
Admittedly, this is probably more work to actually do than going the "try every conceivable bit combination" route, but then you did ask for homework solution ideas. :)
The truth table as summarized on Wikipedia here and gasp, basic CS 101 stuff, De Morgan's Law....
AND
0 & 0 0
0 & 1 0
1 & 0 0
1 & 1 1
OR
0 | 0 0
0 | 1 1
1 | 0 1
0 | 0 1
XOR
0 ^ 0 0
0 ^ 1 1
1 ^ 0 1
1 ^ 1 0
A Shift Left involves shifting the bits across from right to left, suppose:
+-+-+-+-+-+-+-+-+
|7|6|5|4|3|2|1|0|
+-+-+-+-+-+-+-+-+
|0|0|0|0|0|1|0|0| = 0x4 hexadecimal or 4 decimal or 100 in binary
+-+-+-+-+-+-+-+-+
Shift Left by 2 places becomes
+-+-+-+-+-+-+-+-+
|7|6|5|4|3|2|1|0|
+-+-+-+-+-+-+-+-+
|0|0|0|1|0|0|0|0| = 0x10 hexadecimal or 16 decimal or 10000 in binary
+-+-+-+-+-+-+-+-+
Shift Right by 1 places becomes
+-+-+-+-+-+-+-+-+
|7|6|5|4|3|2|1|0|
+-+-+-+-+-+-+-+-+
|0|0|0|0|1|0|0|0| = 0x8 hexadecimal or 8 decimal or 1000 in binary
+-+-+-+-+-+-+-+-+
Then it is a matter of combining the bit-wise operations according to the truth table above...
I would just expand DeMorgan's law: A or B = not(not A and not B). You can compute not by XORing with all 1 bits.