C - Bitwise manipulation - c

I'm very new to C and i'm trying to understand bitwise operators in C
I found this code in front of me (to convert 2 to 37)
int main(void)
{
int x = 2;
x = (x<<x<<x) | (x<<x<<x) | (x << !!x) | !!x ;
printf("%d\n" , x ); // prints 37
}
Now it's the first time i see something like this (x<<x<<x) and i don't understand what it is doing.
Can anyone please explain the second line in code in detail?

I'd recommend you to split this long line into few small pieces (sometimes it is more effective to try such things; i.e. reading of the documentation only is not enough):
int x = 2;
printf("%d\n", x); // prints 2
printf("%d\n", x << x); // prints 8
printf("%d\n", x << x << x); // prints 32
printf("%d\n", !!x); // prints 1
printf("%d\n", x << !!x); // prints 4
printf("%d\n", x); // prints 2 (just to become sure that x was not changed)
So, you know that initial long line is equal to x = (32 | 32 | 1 | 4). But this is 32+4+1=37.
Let's see in details:
What is << and >>?
The shift operators bitwise shift the value on their left by the number of bits on their right:
<< shifts left and adds zeros at the right end.
>> shifts right and adds either 0s, if value is an unsigned type, or extends the top bit (to preserve the sign) if its a signed type.
Also the C standard says about E1 >> E2: "If E1 has a signed type and a negative value, the resulting value is implementation-defined." Arithmetic shift is not guaranteed.
Since << is left associative, x<<x<<x is evaluated as (x<<x)<<x.
See also: What are bitwise shift (bit-shift) operators and how do they work?
What is !!x?
It is an unary NOT and an unary NOT.
!!x can be used as shorthand for (x != 0 ? 1 : 0).

This is known as "obfuscation": writing needlessly complex code in order to make something seem more advanced that it is.
Looking at the sub-expression x<<x<<x, it is simple logical left shifts. The operator associativity of shift operators is left-to-right, so the expression is equal to (x<<x)<<x.
We left shift
2 by 2 and get 8. 8 << 2, left shift 8 by 2 and get 32:
x = 32 | 32 | (x << !!x) | !!x ;
Then for any expression with bitwise OR 32 | 32 where the operands 32 are identical, is the very same thing as just writing 32 without the OR. So it is equivalent to:
x = 32 | (x << !!x) | !!x ;
!! is a somewhat common though obscure trick in C to convert any integer to a boolean value 0 or 1. !! is not one operator, but two times the logical not operator !. First we have !2 which is 0. Then !0 which gives 1. We are left with this:
x = 32 | (2 << 1) | 1;
2 << 1 is 4, so:
x = 32 | 4 | 1;
Write it in binary:
0010 0000
OR 0000 0100
OR 0000 0001
------------
0010 0101 = 0x25 hex = 37 dec

Related

Value of x when s = x >> 31 and x = (s & ~x) | (~s & x);

If x was to equal 12 in a 32 bit scenario, x = multiple 0's into the lsb 0000 1100. If the above scenario were to run, I believe I would get 0000 1100. Am I wrong?
Along with that, what if I was to use x=-1? Wouldn't s = 1, but then does (s & ~x) look like (0001 & 0000) and (1110 & 1111)? Thanks
I thought that x=-1 would mean x>>31 would be like 0001 (output 1), but I don't know if the above is correct.
The typical implementation of a right shift of a signed integer is an arithmetic shift. Different implementations are unfortunately still allowed, though rare, and they're not relevant to understanding this code (it ignores such possibilities anyway). Two's complement integers are now mandatory (in C23: "The sign representation defined in this document is called two’s complement. Previous revisions of this document
additionally allowed other sign representation") so I'm not going to do the usual consideration of hypothetical integer representations that haven't been seen since the stone age.
By assumption the number of bits in an int is 32, so shifting an int right by 31 makes every bit of the result a copy of the sign bit. So if x was negative, s would be -1.
x = (s & ~x) | (~s & x) is a verbose way to spell out x ^= s. XORing x by 0 leaves it the same as before, XORing it by -1 inverts all the bits. Taking into account that s = x < 0 ? -1 : 0, effectively the computation does this:
if (x < 0)
x = ~x; // equivalent to: x = -x - 1;

Using |= for CLI argument parsing [duplicate]

I'm someone who writes code just for fun and haven't really delved into it in either an academic or professional setting, so stuff like these bitwise operators really escapes me.
I was reading an article about JavaScript, which apparently supports bitwise operations. I keep seeing this operation mentioned in places, and I've tried reading about to figure out what exactly it is, but I just don't seem to get it at all. So what are they? Clear examples would be great! :D
Just a few more questions - what are some practical applications of bitwise operations? When might you use them?
Since nobody has broached the subject of why these are useful:
I use bitwise operations a lot when working with flags. For example, if you want to pass a series of flags to an operation (say, File.Open(), with Read mode and Write mode both enabled), you could pass them as a single value. This is accomplished by assigning each possible flag it's own bit in a bitset (byte, short, int, or long). For example:
Read: 00000001
Write: 00000010
So if you want to pass read AND write, you would pass (READ | WRITE) which then combines the two into
00000011
Which then can be decrypted on the other end like:
if ((flag & Read) != 0) { //...
which checks
00000011 &
00000001
which returns
00000001
which is not 0, so the flag does specify READ.
You can use XOR to toggle various bits. I've used this when using a flag to specify directional inputs (Up, Down, Left, Right). For example, if a sprite is moving horizontally, and I want it to turn around:
Up: 00000001
Down: 00000010
Left: 00000100
Right: 00001000
Current: 00000100
I simply XOR the current value with (LEFT | RIGHT) which will turn LEFT off and RIGHT on, in this case.
Bit Shifting is useful in several cases.
x << y
is the same as
x * 2y
if you need to quickly multiply by a power of two, but watch out for shifting a 1-bit into the top bit - this makes the number negative unless it's unsigned. It's also useful when dealing with different sizes of data. For example, reading an integer from four bytes:
int val = (A << 24) | (B << 16) | (C << 8) | D;
Assuming that A is the most-significant byte and D the least. It would end up as:
A = 01000000
B = 00000101
C = 00101011
D = 11100011
val = 01000000 00000101 00101011 11100011
Colors are often stored this way (with the most significant byte either ignored or used as Alpha):
A = 255 = 11111111
R = 21 = 00010101
G = 255 = 11111111
B = 0 = 00000000
Color = 11111111 00010101 11111111 00000000
To find the values again, just shift the bits to the right until it's at the bottom, then mask off the remaining higher-order bits:
Int Alpha = Color >> 24
Int Red = Color >> 16 & 0xFF
Int Green = Color >> 8 & 0xFF
Int Blue = Color & 0xFF
0xFF is the same as 11111111. So essentially, for Red, you would be doing this:
Color >> 16 = (filled in 00000000 00000000)11111111 00010101 (removed 11111111 00000000)
00000000 00000000 11111111 00010101 &
00000000 00000000 00000000 11111111 =
00000000 00000000 00000000 00010101 (The original value)
It is worth noting that the single-bit truth tables listed as other answers work on only one or two input bits at a time. What happens when you use integers, such as:
int x = 5 & 6;
The answer lies in the binary expansion of each input:
5 = 0 0 0 0 0 1 0 1
& 6 = 0 0 0 0 0 1 1 0
---------------------
0 0 0 0 0 1 0 0
Each pair of bits in each column is run through the "AND" function to give the corresponding output bit on the bottom line. So the answer to the above expression is 4. The CPU has done (in this example) 8 separate "AND" operations in parallel, one for each column.
I mention this because I still remember having this "AHA!" moment when I learned about this many years ago.
Bitwise operators are operators that work on a bit at a time.
AND is 1 only if both of its inputs are 1.
OR is 1 if one or more of its inputs are 1.
XOR is 1 only if exactly one of its inputs are 1.
NOT is 1 only if its input are 0.
These can be best described as truth tables. Inputs possibilities are on the top and left, the resultant bit is one of the four (two in the case of NOT since it only has one input) values shown at the intersection of the two inputs.
AND|0 1 OR|0 1
---+---- ---+----
0|0 0 0|0 1
1|0 1 1|1 1
XOR|0 1 NOT|0 1
---+---- ---+---
0|0 1 |1 0
1|1 0
One example is if you only want the lower 4 bits of an integer, you AND it with 15 (binary 1111) so:
203: 1100 1011
AND 15: 0000 1111
------------------
IS 11: 0000 1011
These are the bitwise operators, all supported in JavaScript:
op1 & op2 -- The AND operator compares two bits and generates a result of 1 if both bits are 1; otherwise, it returns 0.
op1 | op2 -- The OR operator compares two bits and generates a result of 1 if the bits are complementary; otherwise, it returns 0.
op1 ^ op2 -- The EXCLUSIVE-OR operator compares two bits and returns 1 if either of the bits are 1 and it gives 0 if both bits are 0 or 1.
~op1 -- The COMPLEMENT operator is used to invert all of the bits of the operand.
op1 << op2 -- The SHIFT LEFT operator moves the bits to the left, discards the far left bit, and assigns the rightmost bit a value of 0. Each move to the left effectively multiplies op1 by 2.
op1 >> op2 -- The SHIFT RIGHT operator moves the bits to the right, discards the far right bit, and assigns the leftmost bit a value of 0. Each move to the right effectively divides op1 in half. The left-most sign bit is preserved.
op1 >>> op2 -- The SHIFT RIGHT - ZERO FILL operator moves the bits to the right, discards the far right bit, and assigns the leftmost bit a value of 0. Each move to the right effectively divides op1 in half. The left-most sign bit is discarded.
In digital computer programming, a bitwise operation operates on one or more bit patterns or binary numerals at the level of their individual bits. It is a fast, primitive action directly supported by the processor, and is used to manipulate values for comparisons and calculations.
operations:
bitwise AND
bitwise OR
bitwise NOT
bitwise XOR
etc
List item
AND|0 1 OR|0 1
---+---- ---+----
0|0 0 0|0 1
1|0 1 1|1 1
XOR|0 1 NOT|0 1
---+---- ---+---
0|0 1 |1 0
1|1 0
Eg.
203: 1100 1011
AND 15: 0000 1111
------------------
= 11: 0000 1011
Uses of bitwise operator
The left-shift and right-shift operators are equivalent to multiplication and division by x * 2y respectively.
Eg.
int main()
{
int x = 19;
printf ("x << 1 = %d\n" , x <<1);
printf ("x >> 1 = %d\n", x >>1);
return 0;
}
// Output: 38 9
The & operator can be used to quickly check if a number is odd or even
Eg.
int main()
{
int x = 19;
(x & 1)? printf("Odd"): printf("Even");
return 0;
}
// Output: Odd
Quick find minimum of x and y without if else statement
Eg.
int min(int x, int y)
{
return y ^ ((x ^ y) & - (x < y))
}
Decimal to binary
conversion
Eg.
#include <stdio.h>
int main ()
{
int n , c , k ;
printf("Enter an integer in decimal number system\n " ) ;
scanf( "%d" , & n );
printf("%d in binary number
system is: \n " , n ) ;
for ( c = 31; c >= 0 ; c -- )
{
k = n >> c ;
if ( k & 1 )
printf("1" ) ;
else
printf("0" ) ;
}
printf(" \n " );
return 0 ;
}
The XOR gate encryption is popular technique, because of its complixblity and reare use by the programmer.
bitwise XOR operator is the most useful operator from technical interview perspective.
bitwise shifting works only with +ve number
Also there is a wide range of use of bitwise logic
To break it down a bit more, it has a lot to do with the binary representation of the value in question.
For example (in decimal):
x = 8
y = 1
would come out to (in binary):
x = 1000
y = 0001
From there, you can do computational operations such as 'and' or 'or'; in this case:
x | y =
1000
0001 |
------
1001
or...9 in decimal
Hope this helps.
When the term "bitwise" is mentioned, it is sometimes clarifying that is is not a "logical" operator.
For example in JavaScript, bitwise operators treat their operands as a sequence of 32 bits (zeros and ones); meanwhile, logical operators are typically used with Boolean (logical) values but can work with non-Boolean types.
Take expr1 && expr2 for example.
Returns expr1 if it can be converted
to false; otherwise, returns expr2.
Thus, when used with Boolean values,
&& returns true if both operands are
true; otherwise, returns false.
a = "Cat" && "Dog" // t && t returns Dog
a = 2 && 4 // t && t returns 4
As others have noted, 2 & 4 is a bitwise AND, so it will return 0.
You can copy the following to test.html or something and test:
<html>
<body>
<script>
alert("\"Cat\" && \"Dog\" = " + ("Cat" && "Dog") + "\n"
+ "2 && 4 = " + (2 && 4) + "\n"
+ "2 & 4 = " + (2 & 4));
</script>
It might help to think of it this way. This is how AND (&) works:
It basically says are both of these numbers ones, so if you have two numbers 5 and 3 they will be converted into binary and the computer will think
5: 00000101
3: 00000011
are both one: 00000001
0 is false, 1 is true
So the AND of 5 and 3 is one. The OR (|) operator does the same thing except only one of the numbers must be one to output 1, not both.
I kept hearing about how slow JavaScript bitwise operators were. I did some tests for my latest blog post and found out they were 40% to 80% faster than the arithmetic alternative in several tests. Perhaps they used to be slow. In modern browsers, I love them.
I have one case in my code that will be faster and easier to read because of this. I'll keep my eyes open for more.

C - Saturating Signed Integer Multiplication with Bitwise Operators

Alright, so the assignment I have to do is to multiply a signed integer by 2 and return the value. If the value overflows then saturate it by returning Tmin or Tmax instead. The challenge is using only these logical operators (! ~ & ^ | + << >>) with no (if statements, loops, etc.) and only allowed a maximum of 20 logical operators.
Now my thought process to tackle this problem was first to find the limits. So I divided Tmin/max by 2 to get the boundaries. Here's what I have:
Positive
This and higher works:
1100000...
This and lower doesn't:
1011111...
If it doesn't work I need to return this:
100000...
Negative
This and lower works:
0011111...
This and higher doesn't:
0100000...
If it doesn't work I need to return this:
011111...
Otherwise I have to return:
2 * x;
(the integers are 32-bit by the way)
I see that the first two bits are important in determining whether or not the problem should return 2*x or the limits. For example an XOR would do since if the first to bits are the same then 2*x should be returned otherwise the limits should be returned. Another if statement is then needed for the sign of the integer for it is negative Tmin needs to be returned, otherwise Tmax needs to be.
Now my question is, how do you do this without using if statements? xD Or a better question is the way I am planning this out going to work or even feasible under the constraints? Or even better question is whether there is an easier way to solve this, and if so how? Any help would be greatly appreciated!
a = (x>>31); // fills the integer with the sign bit
b = (x<<1) >> 31; // fills the integer with the MSB
x <<= 1; // multiplies by 2
x ^= (a^b)&(x^b^0x80000000); // saturate
So how does this work. The first two lines use the arithmetic right shift to fill the whole integer with a selected bit.
The last line is basically the "if statement". If a==b then the right hand side evaluates to 0 and none of the bits in x are flipped. Otherwise it must be the case that a==~b and the right hand side evaluates to x^b^0x80000000.
After the statement is applied x will equal x^x^b^0x80000000 => b^0x80000000 which is exactly the saturation value.
Edit:
Here is it in the context of an actual program.
#include<stdio.h>
main(){
int i = 0xFFFF;
while(i<<=1){
int a = i >> 31;
int b = (i << 1) >> 31;
int x = i << 1;
x ^= (a^b) & (x ^ b ^ 0x80000000);
printf("%d, %d\n", i, x);
}
}
You have a very good starting point. One possible solution is to look at the first two bits.
abxx xxxx
Multiplication by 2 is equivalent to a left shift. So our result would be
bxxx xxx0
We see if b = 1 then we have to apply our special logic. The result in such a case would be
accc cccc
where c = ~a. Thus if we started with bitmasks
m1 = 0bbb bbbb
m2 = b000 0000
m3 = aaaa aaaa & bbbb bbbb
then when b = 1,
x << 1; // gives 1xxx xxxx
x |= m1; // gives 1111 1111
x ^= m2; // gives 0111 1111
x ^= m3; // gives accc cccc (flips bits for initially negative values)
Clearly when b = 0 none of our special logic happens. It's straightforward to get these bitmasks in just a few operations. Disclaimer: I haven't tested this.

Is there an equivalent & expression in C for >> 31

I am trying to understand a CRC-32 algorithm. Is there an equivalent expression for:
y = (X >> 31) ^ (data >> 7);
using &, something like
y = (x & 0x8000) ^ (data & 0x800)
Well it depends on your calculations but in bit operations each operator has its own motive to do things. Same answer can be obtained by different operations but that doesn't mean that operator to equivalent to each other. Each operator has different motive to achieve.
bit a bit b a & b (a AND b) a | b (a OR b) a ^ b (a XOR b)
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
The purpose of << and >> is to shit bits/drop bits from calculations
Right Shift
The symbol of right shift operator is >>. For its operation, it requires two operands. It shifts each bit in its left operand to the right. The number following the operator decides the number of places the bits are shifted (i.e. the right operand). Thus by doing ch >> 3 all the bits will be shifted to the right by three places and so on.
i = 14; // Bit pattern 1110
j = i >> 1; // bit pattern shifted 1 thus we get 111 = 7 = 14/2
Left shift
The symbol of left shift operator is <<. It shifts each bit in its left-hand operand to the left by the number of positions indicated by the right-hand operand. It works opposite to that of right shift operator. Thus by doing ch << 1 in the above example we have 11001010. Blank spaces generated are filled up by zeroes as above.
Left shift can be used to multiply an integer in multiples of 2 as in:
int i = 4; /* bit pattern equivalent is 100 */
int j = i << 2; /* makes it 10000, original number by 4 i.e. 16 */

understanding some C code

Quick question. I've never had experience with C.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, x;
printf( "How many disks? " );
scanf( "%d", &n );
printf("\n");
for (x=1; x < (1 << n); x++)
printf( "move from tower %i to tower %i.\n",(x&x-1)%3, ((x|x-1)+1)%3 );
return 0;
}
This is an iterative tower of hanoi. What do things like (x&x-1) and (x|x-1)+1 mean? I figure the % is doing modulus. and %i is a way of printing out integers in C?
Thanks
The & operator, like the * operator1 can be used for two different things depending on whether it's used as a binary or unary operator.
Unary & like &var takes the address of var. This is necessary to pass it to scanf.
Binary & like var & var is a bitwise AND, like item #2.
Notice that the spacing doesn't matter. What does matter is if there's operands on both sides of the &. So & var is still unary & and var &var is still binary &.
(x&x-1) is doing a bitwise AND with x and x-1.
(x|x-1) is doing a bitwise OR with x and x-1.
Yes % means modulus.
1 << n is doing a bitwise shift of 1 to the left n digits
the %i you are seeing as the first argument to printf are format symbols to which specify that the next argument is an int, so that printf can print it properly (because it doesn't know what type it is by itself, so you have to tell it). It has nothing to do with modulus. You can see a very in-depth definition of printf here: http://pubs.opengroup.org/onlinepubs/9699919799/ (thanks pmg)
If %i were outside a string, it would be to the left of some other operand, and mean modulus.
%i in a string doesn't mean anything by itself. It only means something to printf because printf treats it specially. It searches the string it gets for occurrences of %format (where format is a format, not the word "format") and does something depending on what format it encounters.
1 The * operator also has two different versions: a unary version and a binary version. The unary version means pointer indirection, and the binary version means multiplication.
What do things like (x&x-1) and (x|x-1)+1 mean?
(x&x-1) is equivalent to (x & (x-1)). & is the bitwise-AND operator. Similarly for the second example, where | is the bitwise-OR operator.
I figure the % is doing modulus.
Yes.
and %i is a way of printing out integers in C?
Yes.
| is bitwise OR.
& is bitwise AND.
<< is bitwise shift.
% is modulus.
%i format string prints an integer.
printf is a formatted output function, in which %i means that the argument is an integer. More information is availible here for instance.
The % operator is indeed modulus. & is bitwise AND, and | is bitwise OR.
The line:
for (x=1; x < (1 << n); x++)
initializes x to 1 and repeats/iterates until x < (1 left shifted by n). The left shift basically moves the binary representation of 1 left n binary spaces. so, 0001 would be 0010 after left shifting 1 - this is similar to multiplying by 2^n. x is then increased by 1 (x++). Eventually the increase of x should eventually cause the loop to terminate due to the x < (1 << n) condition.
(x&x-1)%3
Says "The remainder of value x (binary and) value x-1 divided by 3. So, if x is 4, and we're using a 4 bit number (stupid, I know - but it shows the point):
0100 &
0011
_______
0000 (binary and means both spots being added are 1, none are here).
= 0
0/3 = 0 R 0 - no remainder here, so print 0.
The next statement:
(x|x-1)+1)%3
Says x (binary or) x-1, with 1 added to that value. The whole sum there is modded by 3 which is again diving it by 3 and taking the remainder, so if x is 4 again and we're using 4 bit integers:
0100 |
0011
_______
0111 (Binary or means either binary number has a 1 in that slot).
= 4 + 2 + 1 = 7 --> 7 mod 3 = 7 / 3 --> 2 R 1, print remainder of 1 here.
printf allows formatted print out of a variable length list of arguments which can be expressions, so here it will print:
move from tower 0 to tower 1 <new line>
Replacing the %i's with our answers.
& and | are bitwise operators (respectively, AND and OR operators).
0101 (decimal 5)
& 0011 (decimal 3)
------
= 0001 (decimal 1)
0101 (decimal 5)
| 0011 (decimal 3)
------
= 0111 (decimal 7)
Since the substraction operator's precedence is higher than bitwise operators' precedence :
(x&x-1) = (x&(x-1))
(x|x-1) = (x|(x-1))
More informations : http://en.wikipedia.org/wiki/Boolean_algebra

Resources