why we can't print the value in binary form li

2019-08-18 23:21发布

问题:

This question already has an answer here:

  • Is there a printf converter to print in binary format? 48 answers

Why can't we print a number in binary like other in C programming.

Example:

int a=9;  
printf("%b",a);   

like we can print in other form:

  • octal printf("%o",a);
  • decimal printf("%d",a);
  • hexadecimal printf("%x",a);

回答1:

This has nothing to do with C language, per se. It's just that, the C standard does not specify a format specifier for printf() and family to produce a binary representation output, by default.

You can always roll out your own function to get the job done. There are some versions of C library which chose to provide a format specifier (and an integer suffix also) to denote binary representation but once again, that is neither mandated not regulated by the official standard.



回答2:

I'm speculating here, but: C was originally designed and implemented by professional, practicing programmers, with the intent of writing real programs in it. And, while real programs find it necessary and useful to print in decimal and hexadecimal all the time, it's not usually important to print things in binary. It takes a lot of space, and if you're a professional programmer and you have a number that you're thinking about in binary terms, e.g. a bitmask of some kind, it's traditional to print it in the more compact hexadecimal representation, then convert to binary in your head if you need to.

Certainly, printing things in binary is keenly interesting to student programmers, if for no other reason than that their instructors are always assigning it as an exercise. But of course C was never designed with beginning programmers in mind.

If (as I suggested above) it's decimal and hexadecimal that are most common and useful, you might reasonably ask, then why does printf support %o? The answer there, it has been said, is simply that octal was the traditional way of representing machine constants and other binary-ish numbers in machine language on the PDP-11, which was of course C's original platform.

See also question 20.11 in the C FAQ list.



标签: c printf