1

so i have this function that returns a binary representation in c:

long int int2bin(int d)
{
    int rem, pow = 1;
    long int b = 0; 
    while(d > 0) 
    {
        rem = d % 2 ;
        b += (pow * rem);
        d /= 2;
        pow *= 10;
    }

    return b;
}

so from this i was wondering how i might go about having a bin2int() function:

long int bin2int( bin b);  

and you would use it like this:

bin2int(10011); 

and i could this

printf("%i\n", bin2int(10011));

to get 19

scruff
  • 49
  • 2
  • 2
    Wouldn't it be better to represent the binary as a string? – flight Sep 05 '11 at 10:31
  • probably yeah. i was just being general. i guess representing it as a string would be the only way to do it other than making a custom type? – scruff Sep 05 '11 at 10:34
  • See [Can I use a binary literal in C or C++](http://stackoverflow.com/questions/2611764/can-i-use-a-binary-literal-in-c-or-c). – Eran Sep 05 '11 at 10:35
  • 1
    The obvious answer seems to be to use the same type as the return type of your function above, i.e. long int. – Paul R Sep 05 '11 at 10:36

3 Answers3

2

Just replace the 2s and 10 in your function with, respectively, 10s and 2.

pmg
  • 106,608
  • 13
  • 126
  • 198
1

Binary, hex and decimal are simply different ways of representing the same number. For instance all these representations equate to the same - 27 in decimal = 0x1b in hex = 0b11011 in binary.

You can specify the number using any format as an argument to a function expecting a number (int, unsigned int, even char etc).

For instance to print your binary number you could do printf("%i\n", 0b10011) which would give you the number 19. You could write the statement as printf("%i\n", 19) (decimal) or printf("%i\n", 0x13) (hex).

arunkumar
  • 32,803
  • 4
  • 32
  • 47
  • 1
    `0b10011` is not standard C. Some compilers support it as an extension. – interjay Sep 05 '11 at 10:48
  • do you know which compilers? im using MSVC (and it doesnt support it, at least not by default). – scruff Sep 05 '11 at 10:50
  • @interjay thanks. I thought as much. I remember seeing code from a long time ago that used macros B8(1011), B16(10001000) to define binary numbers. But now most compilers appear to support the 0b notation right? Or is gcc the exception – arunkumar Sep 05 '11 at 10:52
  • @scruff you could try the bitset class - http://msdn.microsoft.com/en-us/library/2f93c55z(v=VS.80).aspx – arunkumar Sep 05 '11 at 10:55
  • @arunkumar thanks but i dont really wanna go mixing c++ into this. anyway i just tested gcc and it understands 0b10101 no problems. cool. – scruff Sep 05 '11 at 11:14
0

In pseudo code:

int result = 0;
int ci = 1;
string s = stringof(10011).reverse();
for(int z=0; z < s.length; z++,ci = ci * 2)
{
   if(s[z] == '1')
      result += ci;
}
Ankur
  • 33,367
  • 2
  • 46
  • 72