0

I need to change decimal to binary, saving each digit in an array of size ten.

Actually, I could simply change decimal to binary, but I'm having difficulty with its digits.

Suppose that int a = 3, then its binary form is 11.

But I need to save it in a single dimension array of size 10, to print as 0000000011, not just 11.

To give one more example, if I input decimal 87, my code should print 01010111.

How can I calculate each digit and save them into their proper location in the array?

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
JDFSH
  • 3
  • 1
  • 1
    Possible duplicate of [Convert decimal to binary in C](https://stackoverflow.com/questions/14280336/convert-decimal-to-binary-in-c) – dash-o Oct 26 '19 at 15:44
  • 2
    Can you explain why you need an array of size ten? Bits are stored by power of 2. 4 bits, 8 bits,16 bits, 32 bits etc. 10 bits won't allow to store the max value allowed for a 16 bit integer, and is gonna be empty for 2 bits at least, for an 8 bit integer. Also, are you expecting signed integers? There's a bit reserved to store the sign if so. It's the leftmost one on little endian architectures and right most on big endian architectures. There are a lot of questions to be answered before solving your problem. – axelduch Oct 26 '19 at 16:07
  • regarding: `01010111.` this is `0x67`, not `0xB7` This kind of error could be a root cause of a lot of your confusion. Perhaps you meant: `10110111`. – user3629249 Oct 27 '19 at 01:03

2 Answers2

0

I can't test it right now, but this could help:

// Here there should be the necessary include to enable printing

unsigned int size = 10; // The size of the array that should store the bin output
int          a    = 3;  // The int to be converted to bin

// A function that returns a pointer to a byte, that will be interpreted as an array
unsigned short int
*IntToBin (int input)
{
    static unsigned short int output[size]; // Declaring the array to be returned by
                                            // the function, with keyword 'static' to
                                            // allow it to be referenced from outside
    for (int i = 0; i < size; i++) {
        output[i] = (input >> (size - 1 - i)) & 0x1; // Populating output array by
                                                     // bit-shifting the input int
                                                     // and doing a bitwise 'and' to
                                                     // keep only least significant
                                                     // digit
    }
    return output; // Returning the output array (an array is essentially a pointer,
                   // so this matches the function declaration)
}

// The main function, that will take care of calling the conversion function and
// printing its output
void
main ()
{
    unsigned short int result[] = IntToBin (a); // Assigns the output of the conversion
                                           // function to an array
    // Prints the input and output of the conversion function
    print("a = ");
    print(a);
    print("\na in bin = ");
    for (int i = 0; i < size; i++) {
        print (result[i]);
    }
    print("\n");
}

But, as mentioned in the comments, the behaviour of a signed int is different than that of an unsigned int. And a length of 10 to your output array is a bit strange.

https://www.tutorialspoint.com/cprogramming/c_bitwise_operators.htm

Micael Jarniac
  • 156
  • 1
  • 9
0

The trick with looking at the bits of a number n is to bitwise and with 1 to get the least significant bit then shift right by one bit and then bitwise and with 1 again to get the bit at the second position and so on.

n>>1 & 0x1

Now to store it in an array you should notice that the least significant bit should go in the last element of the array, so if the array a is of size is 10. The least significant bit should be in a[9]

Combining these two you will count the array index from the last position to zero and shift your number to get the bit at that position. Now what you store in the array is not 0 and 1 but the character '0' and character '1'. You can convert the number 0 to character 0 by adding it to '0' and the number 1 by adding 1 to '0'.

Combining all the above ideas you get the code below.

void int2bin(int n, char* b, int sz) {
    for (int p=sz-1; p>=0; p--,n>>=1) {
        b[p] = '0' + (n & 0x1);
    }   
}

int main(int argc, char**argv){
    char a[10]={'0'};
    int2bin(atoi(argv[1]),a,sizeof(a));

    for (int i=0;i<sizeof(a);++i)
        printf("%c",a[i]);

    return 0;
}

Just keep in mind that with array size of 10 the maximum number you can represent in binary is 2^10 - 1 = 1023. If you also consider negative numbers then the maximum in 2^9 -1 =511 and the minimum -512

AliA
  • 690
  • 6
  • 8