0


In c++ when we say cout << x ; // x is an integer, we see on the screen the decimal value of it.
So basically my question is how does the computer/c++ or who ever handles that part, converts from the binary representation to decimal representation.
It can't be a series of integer division(/) and module(%) operations? Can it? Sure there is something more efficient for doing so. Or that's just it?

Abhineet
  • 5,320
  • 1
  • 25
  • 43
DanMaklen
  • 217
  • 3
  • 9
  • A series of bitshifts would probably be more effective. I would imagine it's either done on a hardware level or in the iostream, but I'm a bit curious as well. :) I mean, the number is not converted, it's just displayed differently. – Jaciq Aug 12 '15 at 07:34
  • 1
    Read about format specifiers and you will get some idea on lower level of cout working. – Abhineet Aug 12 '15 at 07:38
  • @Jaciq `cout <<` is not bitshift but predefined operator. – i486 Aug 12 '15 at 07:38
  • @i486 I know. I meant that if a conversion was to be done in a matter similar to a series of integer divisions, a series of bitshift would probably be more effective. – Jaciq Aug 12 '15 at 07:42
  • Compared to drawing bitmapped images of digits on screen, a few modulo operations take no time at all. – Bo Persson Aug 12 '15 at 07:43
  • Why do you think it couldn't be a series of divisions and modulos? That's probably just what it is. Computers are really good at arithmetic like this. – Barmar Aug 12 '15 at 07:51
  • Writing a function to convert integers to decimal is often a homework problem in first-year programming classes. That's generally how it's done. – Barmar Aug 12 '15 at 07:53
  • @Jaciq Bitshifts would be more appropriate when converting to octal or hex. Decimal digits don't correspond directly to any bit positions, so `/10` and `%10` are needed. – Barmar Aug 12 '15 at 07:54
  • @Barmar But the question was on conversion from binary to decimal. :) – Jaciq Aug 12 '15 at 08:11
  • @Jaciq That's my point. Bitshifts won't work for decimal, so why would they "probably be more effective"? – Barmar Aug 12 '15 at 08:14
  • On older systems, multiplications might be implemented as `x << 3 + x << 1` because it's faster. But modern systems with fast multipliers it might not be as correct as before – phuclv Aug 12 '15 at 08:23
  • Anyway, it is better to use `printf` instead of `cout` for precise formatting, etc. `cout` may be used for quick tests or diagnostic output. – i486 Aug 12 '15 at 08:29

0 Answers0