0

I am trying to understand the number representations in c. If I declare a int number=0; and then assign it a value in binary representation i.e. number= 0b0010, how can I print out 0010 using printf?

Also how can we figure out say the 2nd position of 0010, which in this case is 0? I understand that there is a sprintf function for converting numbers to strings, but it seems only for decimal and hex numbers? Thanks for your help!

  • You don't need to assign a value using a literal in binary. To print a binary representation, check this answer: http://stackoverflow.com/questions/111928/is-there-a-printf-converter-to-print-in-binary-format – Nicolas Miari Oct 10 '14 at 02:22
  • 1
    In C, there is no builtin support for binary literals or printing numbers in binary with `printf()`. You can use hexadecimal, decimal or octal. – Bill Lynch Oct 10 '14 at 02:26
  • `int mask = 0x4; /* or whatever 2nd position means to you */ printf("%d", (number & mask) != 0);` – chux - Reinstate Monica Oct 10 '14 at 03:07

2 Answers2

0

You can not assign values in binary. you can assign in Hexadecimal though.

int number = 0x2;
int mask = 0x4;
int result = 0;
printf("%x\n", number);   // This will print in hex
result = (number & mask);

if(result != 0) {
    printf("Second position is 1\n");
} else {
    printf("Second position is 0");
}
Kapil
  • 31
  • 2
0

I hope this helps you. You enter a number and gives you the binary representation, also it works with negative numbers.

After that you can get the bit from n'th position.

#include <stdio.h>

int main(void)
{
  int nr_to_binary = 0;
  unsigned int mask = 0x80000000;
  int position;

  printf("Number: ");
  scanf("%d", &nr_to_binary);

  int i = (sizeof(nr_to_binary) * 8);

  for(; i > 0; i--)
  {
    printf("%d", (nr_to_binary >> (i - 1)) & 1);
  }


  printf("\nPosition: ");
  scanf("%d", &position);
  printf("\n%d position: %d", position, (nr_to_binary >> position) & 1);

  return 0;
}

Wrote it fast, so excuse me for any mistakes i made.

bitcell
  • 921
  • 8
  • 16