Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does scanf("%i",a) not take binary like 0b101?

Tags:

c

I'm confused about the binary expression like 0b10101:

#include <stdio.h>
int main(void) {
  int a,b;
  b = 0b101;
  scanf("%i",&a);
  printf("the value of a is %d\n", a);
  printf("the value of b is %d\n", b);
}

when I type 0b101,

the output gives me

the value of a is 0;
the value of b is 5;

instead of two 5's as it should be.

Is there any way to make scanf take binary input?

like image 816
mko Avatar asked Jul 22 '12 04:07

mko


1 Answers

Standard C has no specific notation prefix for representing binary notation. Only decimal, octal and hexadecimal are supported. Although the 0b prefix was proposed for C99 (and rejected), so it is probably not unusual to see it implemented in some compilers.

Even if you saw 0b prefix supported by some specific C implementation as an extension (GCC?), it would be rather surprising see it recognized by scanf's %i format specifier, since it would break compatibility with standard implementations. The latter are required to stop reading at b.

Judging by your test results though it appears that the compiler supports 0b... integral literals, while the standard library knows nothing about them. Maybe the documentation for that library has something to say about it, like some extended non-standard format specifier/flag for scanf that makes it recognize 0b... prefixes. I don't see it in GCC docs though.

like image 134
AnT Avatar answered Nov 08 '22 10:11

AnT