the following is a small program from Brian Overland`s book "C++ In Plain English" It converts a number from decimal format to binary format as an example of bit shifting.
My problem is that i cannot follow the logic in the function.
here is the program:
specifically AND (ing) OX8000 with an integer (<OX8000)
produces 0000 0000 0000 0000 so how can bit_set >0 ever be true (but even so how does it produce the binary equivalent of n)
I would appreciate however much excruciating detail is forthcoming.
My problem is that i cannot follow the logic in the function.
here is the program:
Code:
#include<iostream>
#include <stdio.h>
void print_binary(short input_field); //declare function print_binary
int main (){
printf("This program prints the binary equivalent of a short integer\n");
printf("by AND_ing it with Ox8000 and assigning true (1) if the result\n");
printf("is greater than 0 otherwise false (0)\n");
short n ; // declare n as a short integer type
do{
printf("\nEnter a short integer ");
printf("(0 to quit): ");
scanf("%hd",&n);
print_binary(n); // call function
} while (n); // continue to loop while n > 0
}
void print_binary(short input_field) { // function print_biary
int i = 1,bit_set; //declare i (initialised to 1)
// and bit_set
while (i <=16) { //loop while i <= 16. get bit AND result
[B]bit_set=((0x8000 & input_field) > 0);[/B] //this evaluates to 0 or 1.
// equiv of Ox8000 = 1000,0000,0000,0000
printf("%hd",bit_set); //if 0 it prints bool 1 else 0
input_field <<= 1;// move 1 bit to the left
i++;
}
}
produces 0000 0000 0000 0000 so how can bit_set >0 ever be true (but even so how does it produce the binary equivalent of n)
I would appreciate however much excruciating detail is forthcoming.
Comment