Home > c programming language > Binary representation of an int in C

Binary representation of an int in C

Problem

You want to visualize the binary representation of an int in C.

Solution

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

char * int2bin(int i)
{
    size_t bits = sizeof(int) * CHAR_BIT;

    char * str = malloc(bits + 1);
    if(!str) return NULL;
    str[bits] = 0;

    // type punning because signed shift is implementation-defined
    unsigned u = *(unsigned *)&i;
    for(; bits--; u >>= 1)
        str[bits] = u & 1 ? '1' : '0';

    return str;
}

int main()
{
    printf("%s\n", int2bin(0x3d));
    printf("%s\n", int2bin(-0x3d));

    return 0;
}

Output:

00000000000000000000000000111101
11111111111111111111111111000011

In the case of the negative number you can nicely see the two’s complement of the positive number.

I found the C source here.

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: