tags:

views:

147

answers:

3

While reading a book called "Let us C" I read that a function showbit() exists which can show you the bits of the number. There wasn't any special header file mentioned for it. Searched for it on the internet and didn't found anything useful. Is there such a function? I want this to print the binary of decimal numbers. Else please give me a replacement function. Thanks

A: 

If you want to print out the bits of a float, for example you could do something like:

float myFloat = 45.2;
for (int n=0;n<8*sizeof(float);n++) {
    printf("%d",(myFloat>>n)&1);
}
Alexander Rafferty
I have never worked on bits,sorry but I dont know bitshifting.
fahad
Alexander Rafferty
gcc says "error: invalid operands to binary >> (have ‘float’ and ‘int’)".
Edgar Bonet
Edgar Bonet
@Alex: Does this actually compile on your system, much less function correctly?
Potatoswatter
It's just a snippet, so I haven't compiled it. But I see no reason for it not to.
Alexander Rafferty
@Alexander: what about the fact that each of the operands of a shift expression shall have integer type according to ISO C99 6.5.7.2?
ninjalj
A: 

All integers are actually in binary in your computer. Its just that it is turned into a string that is the decimal representation of that value when you try to print it using printf and "%d". If you want to know what it looks like in some other base (e.g. base 2 or binary), you either have to provide the proper printf format string if it exists (e.g. "%x" for hex) or just build that string yourself and print it out.

Here is some code that can build the string representation of an integer in any base in [2,36].

#include <stdio.h>
#include <string.h>

char digits[]="01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";

void reverse(char* start, char* end)
{
    for(end--;start<end;start++,end--)
    {
        char t=*start;
        *start=*end;
        *end=t;
    }
}


int base_change(int n, int base,char* buffer)
{
    int pos=0;
    if (base>strlen(digits)) 
        return -1;
    while(n)
    {
        buffer[pos]=digits[n%base];
        n/=base;
        pos++;
    }
    buffer[pos]='\0';
    reverse(buffer,buffer+pos);
    return 0;
}

int main()
{
    char buffer[32];
    int conv=base_change(1024,2,buffer);
    if (conv==0) printf("%s\n",buffer);
    return 0;
}
MAK
See the code again dear, n/=base;?
fahad
@fahad: huh? What part of `n/=base` do you not understand? Please lookup shortcuts such as `+=`, `*=`, `/=` etc.
MAK
Thanks,understood.
fahad
A: 

you need to look here

@downvoter It works fine in c also. You just need to reformat your code in c-style.

#include <stdlib.h>
#include <stdio.h>
int main()
{
char buffer[20];
int  i = 3445;
_itoa( i, buffer, 2  );
printf("String of integer %d (radix 2): %s",i,buffer);
return 0;
}

*you need to save your file as .c in MSVC++ for _itoa() to work.*

CadetNumber1
Just remove the _ ?
fahad
Thanks,removing the "_" worked.
fahad