Hi, i found this Function to convert any integer into its BINARY VALUE... I could not make it through..
Can someone Help me out.... I need a good explanation on how it works...
Here is the code.

char *binString(int value)
{
 static char bin[17];
 int index;
 
for(index=0;index<16;index++)
{
if(value & 0x8000)   // could not make out, what this does
bin[index]='1';
else
bin[index]='0';
value=value<<1; // and this one
}

bin[16]=0x00; // this one too
 return(bin);
}

Bitwise operators

The last one, line 15, is just null-terminating the string. The author could have simply use 0 instead of 0x00.

I'm asuming you already understand the relationship between hexadecimal(base16), decimal(base10), and binary (base2), and that any integer value can be represented simultaneously by either of these systems.

LINE 8: the hexadecimal value "8000" in binary looks like this "1000 0000 0000 0000"

it is the "bit mask" that checks the highest (most significant) bit in the value being tested.

the check is accomplished by using the "bitwise AND" operator: "&". it performs an AND function on each and every bit in the value against the 0x8000 bitmask. look up "bitwise AND" if you dont understand this.

LINE 12: this shifts the value being tested one bit to the left, causing the next highest bit to become the MSB (most significant bit) and thus be the one that is checked by the bitmask in LINE 8.

this is accomplished by using the "logical shift left" operator: "<<" it shifts each bit one place to the left, dropping the MSB off the left end (lost forever), and padding 0's into the empty LSB spot on the right.

you should use your IDE (development environment) debugging functionality to step through this program and watch the values change in binary and/or hex, along with the string value that contains all '1' and '0' characters to represent the binary value.

Hey thanks for your patience.... understood now.... :icon_smile:

great! apologies if i was being overly explanatory.

:)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.