-1

Recently i saw a code that prints number in binary system.
I dont understand line : bit = (dec & 0x8000) != 0;
Is there's anyone that can explan this to me?

int dec,n ;
short bit;


    printf("Insert number: ");
    scanf("%d", &dec);

    if (dec == 9999)  printf(" Out of range!"); 


    for (int i = 1; i <= 16; i++) {
        bit = (dec & 0x8000) != 0;
        printf("%d", bit);
        if (i % 4 == 0) printf(" ");
        dec <<= 1;
    }
    printf("\n");



return 0;

}

Mangaldeep Pannu
  • 3,738
  • 2
  • 26
  • 45
icancar99
  • 29
  • 5
  • Possible duplicate of [What does this ampersand mean in C?](https://stackoverflow.com/questions/24370797/what-does-this-ampersand-mean-in-c) – phuclv Apr 07 '19 at 15:59

6 Answers6

3

Assign to the variable bit a value of 1 if the result of evaluating (dec & 0x8000) is not equal to 0; and a value of 0 otherwise.

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
2

the value of (dec & 0x8000) != 0 is evaluated first as true or false(1 or 0) and then bit is assigned the value.

Sandeep Polamuri
  • 609
  • 4
  • 10
1

This line takes the number you inserted from console and applies logical AND. For example, if you enter 1024 ( 0100 0000 0000 binary ), then you have 0100 0000 0000 & 1000 0000 0000 0000 ( which is 0x8000, every number is replaced with binary tetrad ). In this case result is 0 which isn't != 0 and then value of variable bit is 0.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
java_brat
  • 72
  • 4
0

The & operator is bitwise-and. It is being used to mask off all bits from dec except bit 0x8000. The != operator is a comparison operator. It tests for two values being unequal. If they are unequal, the result is 1. Otherwise the result is 0. So if bit 0x8000 of dec is non-zero, i.e. 1, then bit will be 1. Otherwise it will be 0.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
0

It tests if the single bit set in the constant 0x8000 is set in dec or not. & is the bitwise and operator.

The result of (dec & 0x8000) != 0 (which is either 0 or 1) is assigned to bit.

Personally I prefer bit = !!(dec & 0x8000).

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

The line

bit = (dec & 0x8000) != 0 ;

is equivalent to:

if ( (dec & 0x8000) != 0 ) bit = 1;
else                       bit = 0;

but it is an one-liner for the if-else statement

& is the bitwise and operator which compares the binary record from dec and 0x8000 and returns the 1's where there are both in dec and 0x8000

little example: 11&5 returns 1 because 11 = 0b1011 and 5 = 0b101 and comparing (from right to left) we have only the last 1 in both numbers...

0x8000 is hexadecimal for 32768

hope this will help

J01337
  • 58
  • 10