Bitwise AND behaves differently than expected? - c

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int a = 50; // 110010
int b = 30; // 011110
if (a & b) {
printf("Hi");
}
return 0;
}
The code above prints Hi.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int a = 50; // 110010
int b = 13; // 001101
if (a & b) {
printf("Hi");
}
return 0;
}
The code above doesn't print anything.
Logically, you would think that a bitwise AND would mean that all the digits in binary would have to match in order to return true. Instead, in reality, each digit in binary would have to be different for the condition to return false.
I don't understand the point of bitwise AND.
I also understand that false is equivalent to 0 in C.

Like Karthik said it's bitwise.
int a = 50; // 110010 int a = 50; // 110010
int b = 30; // 011110 & int b = 13; // 001101 &
¯¯¯¯¯¯¯ ¯¯¯¯¯¯¯
010010 = 18 000000 = 0 --false

It is a bitwise &. That means the result of the operation is the result of applying & bit by bit on the two operands.
int a = 50; // 110010
int b = 30; // 011110
a & b == 010010 == 18 == true
If you want all the bits to be equal, that's just ==. Or you would bitwise & it with 111111

The operator is bitwise, which means it compares the binary representation of two variables bit by bit. When you have
int a = 50; // 110010
int b = 30; // 011110
int result = a & b; // 010010
What happens is this: the bits of result are set based on the values of the bits in a and b. Each pair of corresponding bits in a and b is compared. Here, since the second and fifth bits (from the right) of both a and b are 1, i.e., true, the comparison of those bits yields true, and correspondingly, the second and fifth bits in result are set to true as well. Consequently, result is nonzero. This nonzero evaluation of a & b would cause "Hi" to print in your first example.
In your second example:
int a = 50; // 110010
int b = 13; // 001101
int result = a & b; // 000000
There is no case in the binary representation of 50 and 13 where corresponding bits are on: the first bit (from the right) is off in 50, on in 13; vice-versa for the second bit, and so on. So the comparison of corresponding bits yields 0 in every case, and no corresponding bit is on in result. Hence result evaluates to zero. This zero result causes "Hi" not to print in your second example.
As to the utility of this operator: bitwise operations are essential in embedded systems programming. They are also extremely efficient for certain problems (e.g. a Sieve of Eratosthenes type program to generate primes). The bitwise or is useful in cryptography. The list goes on...

Case 1:
int a = 50; // 110010
int b = 30; // 011110
if (a & b) =>if (50 & 30) => if( 1 1 0 0 1 0 & => if(010010)=> if(18)=>
0 1 1 1 1 0 )
if(18)=>if(TRUE)=> printf("Hi")
Case 2:
int a = 50; // 110010
int b = 13; // 001101
if (a & b) =>if (50 & 13) => if( 1 1 0 0 1 0 & => if(000000)=> if(0)=>
0 0 1 1 0 1 )
if(0)=>if(FALSE) => NO printf("Hi")

What is not clear to you is that in C, the number 0 is false, and any other number is true.
if (0) {
printf("hi");
}
will do nothing, so if the bit-wise-and operation doesn't produce a single set bit, you have effectively computed an if statement that looks like
if (false) {
printf("hi");
}
As everyone else has done a fine example of showing the bit operation, I'll defer to their math.

This is exactly the purpose of the bitwise and. It's mostly used for bit testing with masks. The net effect is to keep all the common 1s and zero out everything else. Say, for instance you want to test if the 3rd bit is 1, you can just write
if ( a & 4 /*0100*/ )
// do something
As Karthik said there are other methods to compare the operands the way you expected.

"Logically, you would think that a bitwise AND would mean that all the digits in binary would have to match in order to return true. Instead, in reality, each digit in binary would have to be different for the condition to return false."
They don't have to be different. AND would yield zero if both bits were zero, for instance. XOR is the logical operator that returns true only if the bits are different, and XNOR is the one that returns true only if they're the same. Since anything non-zero is true, then to get AND to return true you just need any one bit to be 1 in both of the operands. Conversely, it'll return false if neither of the operands have a 1-bit in common.

Related

Problems about check a integer is zero or negative with only operator in C?

/*
* isPower2 - returns 1 if x is a power of 2, and 0 otherwise
* Examples: isPower2(5) = 0, isPower2(8) = 1, isPower2(0) = 0
* Note that no negative number is a power of 2.
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 20
* Rating: 4
*/
int isPower2(int x) {
/*
* Variable a checks if x is power of 2, x and x - 1 won't have a 1
* in the same place if it's power of 2. Variable b checks if x is
* negative or zero. Use & to combine !a and b to complete the function.
*/
int a = x &(x+(~1+1));
int b = ((x+(~1+1))>> 31)+1;
return (!a)&b;
}
Hello every one, I am self-learning a course called CSE351 form Washton University and am finishing the lab1 about data manipulation in C. As you
can see about this question, I need to use the variable b to tell whether or not
the int x is zero.
And then I think that for zero or negative, if you minus one and then right shift 31 bits, adding one, you will get zero if the int is 0, and 1 if it is positive.
But however, my code didn't work, but I found a line of code works.
int b = ((!(x >> 31)) & (~(!x)));
I am really confused why my code don't work, can somebody tell me why?
Edit: Sorry, I didn't mention the environment of this lab is based on int with 32 bits and 2's complement for negative.
Several things to note (in your code):
first, (~1 + 1) is the same as ~0, and the same as -1 (in two's complement). Simpler, right?
x + (~0) is the same as x - 1. Simpler, right?
x & (x - 1) is 1 all the bits that don't change and are 1, when x is decremented. I think what you pretend here is to write x ^ (x - 1) that is, the set of bits that carry to the next on a decrement. This is the bits that change in a decrement. It happens that all bits change iff the number is a power of two. In case you want the bits that don't change, instead of using ^, just use & (bits that are 1 and don't change on a decrement which must be the empty set in case of a power of two ---we have to complement the result, as this boolean gives the opposite) This expression could be the result to get a power of two, if you consider the special case of 0 that is returned as a power of two. As with negatives, and 0, the logarithm does not exist, so we can simply say if (x <= 0) return 0; else return !(x & (x - 1)); (THIS CAN BE THE REQUESTED SOLUTION) or more compact return x <= 0 ? 0 : !(x&(x-1));.
~a as a consequence is _all the bits that do change OR are 0 when x is decremented. I'm lost completely here on what you pretend. I think you want to get if x <= 0 but that's so easy to write in C, instead of the complications you show.
So, your intentions (I guess) is to use the number of 1 bits that don't change on a decrement, because all bits do change for powers of two. Then, a possible implementation should be:
#include <stdio.h>
/*
* isPower2 - returns 1 if x is a power of 2, and 0 otherwise
* Examples: isPower2(5) = 0, isPower2(8) = 1, isPower2(0) = 0
* Note that no negative number is a power of 2. (and zero also, there's no logarithm of zero)
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 20
* Rating: 4
*/
int isPower2(int x) {
return x <= 0
? 0
: !(x&(x-1));
}
/* please, always post complete and verifiable code, with header files,
* and the like, so we can test it without having to first modify it.
*/
int main()
{
for (;;) {
int a;
scanf("%d", &a);
printf("isPower2(a=%d) => %d\n", a, isPower2(a));
}
}
NOTE
Anyway, I don't have a clear idea of the result you want to get, as you entitle the question as Problems about check a integer is zero or negative... and then you show partial code (see How to create a Minimal, Complete, and Verifiable example) about how to detect if some given integer is a power of two but then, you show then some strange code to check if a number is negative. It suffices to do:
if (x <= 0) do_bla_bla();
and this doesn't produce undefined behaviour with 31 bit right shifts.
NOTE
if you need to use only the operators in the list, just change <= by the following:
#define SIGNBIT (~(~0>>1)) /* ALL ONES, SHIFTED ONE BIT RIGHT AND COMPLEMENTED */
return
x & SIGNBIT /* sign bit on, negative number */
|| !x /* OR x == 0 */
? 0
: !(x&(x-1));
The final code is:
#include <stdio.h>
/*
* isPower2 - returns 1 if x is a power of 2, and 0 otherwise
* Examples: isPower2(5) = 0, isPower2(8) = 1, isPower2(0) = 0
* Note that no negative number is a power of 2. (and zero also, there's no logarithm of zero)
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 20
* Rating: 4
*/
#define SIGNBIT (~(~0>>1))
int isPower2(int x) {
return x & SIGNBIT || !x ? 0 : !(x&(x-1));
/* if anybody tells you are using ? and || operators, just write:
* if (x & SIGNBIT) return 0;
* if (!x) return 0;
* return !(x&(x-1));
*/
}
/* please, always post complete and verifiable code, with header files,
* and the like, so we can test it without having to first modify it.
*/
int main()
{
for (;;) {
int a;
scanf("%d", &a);
printf("isPower2(a=%d) => %d\n", a, isPower2(a));
}
}

Iterate through bits in C

I have a big char *str where the first 8 chars (which equals 64 bits if I'm not wrong), represents a bitmap. Is there any way to iterate through these 8 chars and see which bits are 0? I'm having alot of trouble understanding the concept of bits, as you can't "see" them in the code, so I can't think of any way to do this.
Imagine you have only one byte, a single char my_char. You can test for individual bits using bitwise operators and bit shifts.
unsigned char my_char = 0xAA;
int what_bit_i_am_testing = 0;
while (what_bit_i_am_testing < 8) {
if (my_char & 0x01) {
printf("bit %d is 1\n", what_bit_i_am_testing);
}
else {
printf("bit %d is 0\n", what_bit_i_am_testing);
}
what_bit_i_am_testing++;
my_char = my_char >> 1;
}
The part that must be new to you, is the >> operator. This operator will "insert a zero on the left and push every bit to the right, and the rightmost will be thrown away".
That was not a very technical description for a right bit shift of 1.
Here is a way to iterate over each of the set bits of an unsigned integer (use unsigned rather than signed integers for well-defined behaviour; unsigned of any width should be fine), one bit at a time.
Define the following macros:
#define LSBIT(X) ((X) & (-(X)))
#define CLEARLSBIT(X) ((X) & ((X) - 1))
Then you can use the following idiom to iterate over the set bits, LSbit first:
unsigned temp_bits;
unsigned one_bit;
temp_bits = some_value;
for ( ; temp_bits; temp_bits = CLEARLSBIT(temp_bits) ) {
one_bit = LSBIT(temp_bits);
/* Do something with one_bit */
}
I'm not sure whether this suits your needs. You said you want to check for 0 bits, rather than 1 bits — maybe you could bitwise-invert the initial value. Also for multi-byte values, you could put it in another for loop to process one byte/word at a time.
It's true for little-endian memory architecture:
const int cBitmapSize = 8;
const int cBitsCount = cBitmapSize * 8;
const unsigned char cBitmap[cBitmapSize] = /* some data */;
for(int n = 0; n < cBitsCount; n++)
{
unsigned char Mask = 1 << (n % 8);
if(cBitmap[n / 8] & Mask)
{
// if n'th bit is 1...
}
}
In the C language, chars are 8-bit wide bytes, and in general in computer science, data is organized around bytes as the fundamental unit.
In some cases, such as your problem, data is stored as boolean values in individual bits, so we need a way to determine whether a particular bit in a particular byte is on or off. There is already an SO solution for this explaining how to do bit manipulations in C.
To check a bit, the usual method is to AND it with the bit you want to check:
int isBitSet = bitmap & (1 << bit_position);
If the variable isBitSet is 0 after this operation, then the bit is not set. Any other value indicates that the bit is on.
For one char b you can simply iterate like this :
for (int i=0; i<8; i++) {
printf("This is the %d-th bit : %d\n",i,(b>>i)&1);
}
You can then iterate through the chars as needed.
What you should understand is that you cannot manipulate directly the bits, you can just use some arithmetic properties of number in base 2 to compute numbers that in some way represents some bits you want to know.
How does it work for example ? In a char there is 8 bits. A char can be see as a number written with 8 bits in base 2. If the number in b is b7b6b5b4b3b2b1b0 (each being a digit) then b>>i is b shifted to the right by i positions (in the left 0's are pushed). So, 10110111 >> 2 is 00101101, then the operation &1 isolate the last bit (bitwise and operator).
If you want to iterate through all char.
char *str = "MNO"; // M=01001101, N=01001110, O=01001111
int bit = 0;
for (int x = strlen(str)-1; x > -1; x--){ // Start from O, N, M
printf("Char %c \n", str[x]);
for(int y=0; y<8; y++){ // Iterate though every bit
// Shift bit the the right with y step and mask last position
if( str[x]>>y & 0b00000001 ){
printf("bit %d = 1\n", bit);
}else{
printf("bit %d = 0\n", bit);
}
bit++;
}
}
output
Char O
bit 0 = 1
bit 1 = 1
bit 2 = 1
bit 3 = 1
bit 4 = 0
bit 5 = 0
bit 6 = 1
bit 7 = 0
Char N
bit 8 = 0
bit 9 = 1
bit 10 = 1
...

Return 1 if any bits in an integer equal 1 using bit operations in C

I've been thinking about this problem for hours. Here it is:
Write an expression that returns 1 if a given integer "x" has any bits equal to 1. return 0 otherwise.
I understand that I'm essentially just trying to figure out if x == 0 because that is the only int that has no 1 bits, but I can't figure out a solution. You may not use traditional control structures. You may use bitwise operators, addition, subtraction, and bit shifts. Suggestions?
Here's the best I could come up with:
y = (((-x) | x) >> (BITS - 1)) & 1;
where BITS = 32 for 32 bit ints, i.e. BITS = sizeof(int) * CHAR_BIT;
Here's a test program:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int main(int argc, char *argv[])
{
const int BITS = sizeof(int) * CHAR_BIT;
if (argc == 2)
{
int x = atoi(argv[1]);
int y = (((-x) | x) >> (BITS - 1)) & 1;
printf("%d -> %d\n", x, y);
}
return 0;
}
Using !!x will give you the right answer. Since !0 = 1 and !(any nonzero number) = 0.
For a 32-bit value, the following will work for all bit-patterns.
return (a | -a) >> 31;
Mask each of the bits individually, shift them all down to the lsb position, and or them together.
You could just cast your int to a bool. But I doubt that's the purpose of your homework ;-)
For 32 bit integers
int return_not_zero(int v)
{
r=v;
r=(r&0xFFFF) | (r>>16);
r=(r&0xFF) | (r>>8);
r=(r&0x0F) | (r>>4);
r=(r&0x03) | (r>>2);
r=(r&0x01) | (r>>1);
return r;
}
0 || number - this will return 0 only if the number is 0 and will return 1 if the number is any other number than 0. Since a number without any bit as 1 will be equal to 0, we need to check it with 0.
untested, that's the first thing that came to my mind:
while(n & pow(2, e) == 0 && e++ <= 16) ; // 16 or 32
if e == 16 after the loop n is 0.
int any_bits_to_one(unsigned int n) {
int result = 0, i;
for (i=0; !result && i < sizeof(unsigned int) * 8; i++)
result |= (n & (1<<i)) ? 1 : 0;
return result;
}
Bitwise AND with 0 and any number must equal zero, but the only foolproof test would be with 0xFFFF, or every bit being set. To get all bits set, you should have a signed int, and assign it -1. You will then have an int with all bits set to 1, regardless of size.
So my answer would be to bitwise AND it with -1
How about !(x&&~x)&&x ?
#include <stdio.h>
void main(){
int x;
scanf("%d",&x);
printf("%d\n",(!(x&&~x)&&x));
}
It seems work, but I'm not sure when overflow happens.
I believe this is the simplest way.
return !!(0|x);
The only time your x will not have a 1 in it is when all bits are 0, or x == 0. So 0|0 -> 0 else 0|x -> non zero.
In C language, any value other than ZERO (either positive or negative) is treated as TRUE. And there should be a condition to check either your question's solution returns a ZERO or ONE (or other than ZERO). Therefore this answer is perfectly as per your requirement. This uses only bit-wise operators.
return (x & 0xFFFF);
This line returns ZERO when neither of any bit in "x" is 1, and returns Non-Zero (TRUE in a sense) when any of the bit is 1 in "x".

Finding Bit Positions in an unsigned 32-bit integer

I think I might have been asleep in my CS class when they talked about Bit Positions, so I am hoping someone can lend a hand.
I have a unsigned 32-bit integer (Lets use the value: 28)
According to some documentation I am going over, the value of the integer contains flags specifying various things.
Bit positions within the flag are numbered from 1 (low-order) to 32 (high-order).
All undefined flag bits are reserved and must be set to 0.
I have a Table that shows the meanings of the flags, with meaning for the numbers 1-10.
I am hoping that someone can try and explain to me what this all means and how to find the "flag" value(s) from a number like, 28, based off of bit position.
Thanks
28 converts to 11100 in binary. That means bits 1 and 2 are not set and bits 3, 4 and 5 are set.
A few points: first, anybody who's really accustomed to C will usually start the numbering at 0, not 1. Second, you can test of individual flags with the bitwise and operator (&), as in:
#define flag1 1 // 1 = 00 0001
#define flag2 2 // 2 = 00 0010
#define flag3 4 // 4 = 00 0100
#define flag4 8 // 8 = 00 1000
#define flag5 16 // 16 = 01 0000
#define flag6 32 // 32 = 10 0000
if (myvalue & flag1)
// flag1 was set
if (myvalue & flag4)
// flag4 was set
and so on. You can also check which bits are set in a loop:
#include <stdio.h>
int main() {
int myvalue = 28;
int i, iter;
for (i=1, iter=1; i<256; i<<=1, iter++)
if (myvalue & i)
printf("Flag: %d set\n", iter);
return 0;
}
should print:
Flag: 3 set
Flag: 4 set
Flag: 5 set
Instead of looping through every single bit, you can instead loop through only the set bits, which can be faster if you expect bits to be sparsely set:
Assume the bit field is in (scalar integer) variable field.
while (field){
temp = field & -field; //extract least significant bit on a 2s complement machine
field ^= temp; // toggle the bit off
//now you could have a switch statement or bunch of conditionals to test temp
//or get the index of the bit and index into a jump table, etc.
}
Works pretty well when the bit field is not limited to the size of a single data type, but could be of some arbitrary size. In that case, you can extract 32 (or whatever your register size is) bits at a time, test it against 0, and then move on to the next word.
To get an int with the value 0 or 1 representing just the nth bit from that integer, use:
int bitN = (value >> n) & 1;
But that's not usually what you want to do. A more common idiom is this:
int bitN = value & (1 << n);
In this case bitN will be 0 if the nth bit is not set, and non-zero in the case that the nth bit is set. (Specifically, it'll be whatever value comes out with just the nth bit set.)
Assuming flags is unsigned...
int flag_num = 1;
while (flags != 0)
{
if ((flags&1) != 0)
{
printf("Flag %d set\n", flags);
}
flags >>= 1;
flag_num += 1;
}
If flags is signed you should replace
flags >>= 1;
with
flags = (flags >> 1) & 0x7fffffff;
Use a log function, with base 2. In python, that would look like:
import math
position = math.log(value, 2)
If position is not an integer, then more than 1 bit was set to 1.
A slight variation of #invaliddata's answer-
unsigned int tmp_bitmap = x;
while (tmp_bitmap > 0) {
int next_psn = __builtin_ffs(tmp_bitmap) - 1;
tmp_bitmap &= (tmp_bitmap-1);
printf("Flag: %d set\n", next_psn);
}
// You can check the bit set positions of 32 bit integer.
// That's why the check is added "i != 0 && i <= val" to iterate till
// the end bit position.
void find_bit_pos(unsigned int val) {
unsigned int i;
int bit_pos;
printf("%u::\n", val);
for(i = 1, bit_pos = 1; i != 0 && i <= val; i <<= 1, bit_pos++) {
if(val & i)
printf("set bit pos: %d\n", bit_pos);
}
}
An MSVC variation of #boolAeon's answer
#include <vector>
#include <intrin.h>
std::vector<unsigned long> poppos(const unsigned long input)
{
std::vector<unsigned long> result;
result.reserve(sizeof(input) * CHAR_BIT);
unsigned long num = input;
unsigned long index = -1;
while (_BitScanForward(&index, num))
{
result.push_back(index);
num &= num - 1;
}
return result;
}
Let's say that you have an array of integers, and you want to find all the positions (32-bit positions) where the bits are set collectively i.e. for a particular bit position how many set bits you will have in total by considering all the integers. In this case what you can do is that check for every Integer and mark its set bit position :
// let arr[n] is an array of integers of size n.
int fq[33] = {0} // frequency array that will contain frequency of set bits at a particular position as 1 based indexing.
for(int i=0; i<n; i++) {
int x = arr[i];
int pos = 1; // bit position
for(int i=1; i<=pow(2,32); i= i<<1) { // i is the bit mask for checking every position and will go till 2^32 because x is an integer.
if(x & i) fq[pos]++;
pos++;
}
}

Fastest way to count number of bit transitions in an unsigned int

I'm looking for the fastest way of counting the number of bit transitions in an unsigned int.
If the int contains: 0b00000000000000000000000000001010
The number of transitions are: 4
If the int contains: 0b00000000000000000000000000001001
The number of transitions are: 3
Language is C.
int numTransitions(int a)
{
int b = a >> 1; // sign-extending shift properly counts bits at the ends
int c = a ^ b; // xor marks bits that are not the same as their neighbors on the left
return CountBits(c); // count number of set bits in c
}
For an efficient implementation of CountBits see http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
Fastest depends on your scenario:
As you specified your datatype as constant sized (unsigned int), it is possible with lookup table. But when you need this operation only once the constant overhead to init the table is too big, and scanning+counting through the int is far faster despite.
I guess the overall best would be a combination: Look up table for a byte or word (256 or 64k entries is not so much), and then combine the bytes/words by their last/first bit.
In C/C++ I would do the following:
unsigned int Transitions(unsigned int value)
{
unsigned int result = 0;
for (unsigned int markers = value ^ (value >> 1); markers; markers = markers >> 1)
{
if (markers & 0x01) result++;
}
return result;
}
Here's the code using arithmetic shift + xor and Kernighan's method for bit counting:
int count_transitions(int x)
{
assert((-1 >> 1) < 0); // check for arithmetic shift
int count = 0;
for(x ^= (x >> 1); x; x &= x - 1)
++count;
return count;
}
What language?
I would loop 64 times and then bit shift your number to inspect of the bits, then store the previous bit and compare it to the current one. If it's different, incremember your count.
Ok, with transitions you mean if you walk through the string of 0-s and 1-s, you count each occurance that a 0 follows a 1 or a 1 follows a 0.
This is easy by shifting bits out and counting the changes:
transitions(n)
result = 0
prev = n mod 2
n = n div 2
while n<>0
if n mod 2 <> prev then
result++
prev = n mod 2
fi
n = n div 2
elihw
return result
you can replace the mod and div with shifts.

Resources