8 years ago.

Decimal to Binary Conversion Function

Hi,

Would anyone have a Decimal to binary conversion function code example written at all? All that I have seen are using syntax that is native to their language. I need some help to start with.

I wish to take

int = x whatever number and printf("%",x) as binary value

Java has this built in method: Integer.toString(100,2) prints 1100100 binary representation

I have never needed to use this until now Thanks

1 Answer

8 years ago.

There is nothing standard in c. If you know the size of the binary string you want as an output then it's fairly straightforward.

void int2bin(int value, char* buffer, int bufferSize) {
  char *nextChar = buffer + bufferSize-2;            // location to write the least significant bit

  for (int i = 0; i<(bufferSize-1); i++) {                    // for each bit
    (value & (1<<i)) ? *nextChar  = '1' : *nextChar  = '0'; // if set set to '1' else '0'
    nextChar --;
  }

  *(buffer + bufferSize-1) = 0;  // add the null terminator
}

main () {
  int x = 100;
  char binaryBuffer[9]; // 8 bits plus null terminator
  int2bin(x, binaryBuffer, 9) ;
  printf("%d = %s in binary\r\n",x,binaryBuffer);
}

-----

Update

This version will return a char* to the minimum length string required for the value give. Negative values will be 32 bits long or however long the supplied buffer is if it's less. If the buffer isn't large enough for the supplied value then you get the least significant bits, there is no warning that data has been lost.

char* int2bin(int value, char* buffer, int bufferSize)
{
    char *nextChar = buffer + bufferSize-1;            // location to write the least significant bit

    *nextChar = 0;  // add the null terminator

    do {
        nextChar--;
        (value & 1) ? *nextChar  = '1' : *nextChar  = '0'; // if set set to '1' else '0'
        value = value>>1;
        if (nextChar == buffer)
          break;
    } while (value);
    return nextChar;
}

main()
{

    int x = 100;
    char binaryBuffer[17];  //  17 bytes - 16 bits plus a null.
    char* binString = int2bin(x, binaryBuffer, 17) ;
    printf("%d = %s in binary\r\n",x,binString); 

    x = 1234;
    binString = int2bin(x, binaryBuffer, 17) ;
    printf("%d = %s in binary\r\n",x,binString);

    binString = int2bin(x, binaryBuffer, 8) ; // tell it that the buffer is only 8 long - 7 bits plus a null.
    printf("%d = %s in binary\r\n",x,binString);

    x = -256;
    binString = int2bin(x, binaryBuffer, 17) ;
    printf("%d = %s in binary\r\n",x,binString);
}

The output of this is:

100 = 1100100 in binary
1234 = 10011010010 in binary
1234 = 1010010 in binary 
-256 = 1111111100000000 in binary

Accepted Answer

Thank you for you quick response, this is exactly what I was looking for.

posted by ashley sharp 06 Apr 2016