tadm123
tadm123

Reputation: 8795

C decimal to binary converter (16 bits)

I'm trying to convert a decimal number into binary (16 bits max). My function works perfectly for up to 8 bits but when I want to print numbers up to 16 bits, it stop printing characters. I used "int" as my data type for 8 bits but since I want to store 16 bits I'm using an unsigned long int in every variable.

Here's the code:

/* Program to convert decimal to binary (16 bits) */

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

char *byte_to_binary_str(long unsigned int byte);

int main()
{

 printf("%s",byte_to_binary_str(32768));  //1000000 0000000
    return 0;
}

char *byte_to_binary_str(long unsigned int byte)
{
    static char bit_string[17];
    bit_string[0] = '\0';

    long unsigned int mask;
    for (mask = 2^15; mask > 0; mask >>= 1) {
        /* Check if the mask bit is set */
        strcat(bit_string, byte & mask ? "1" : "0");
    }

    return bit_string;
}

My output gives me:

0000
Process returned 0 (0x0)   execution time : 0.063 s
Press any key to continue.

Anyone know why is this happening? Thanks in advance.

Upvotes: 1

Views: 4057

Answers (1)

R Sahu
R Sahu

Reputation: 206607

mask = 2^15;

does not set the value of mask to what you are expecting 2^15 is no 2 raised to the power 15. It is bitwise XOR of 2 and 15.

You need something that is 1000 0000 0000 0000 in binary. That number will be 0x8000 in hex. Hence, use:

mask = 0x8000;

You can also use something that makes sense in your algorithm.

mask = 1u << 15;

Upvotes: 4

Related Questions