Question 20.10

How can I convert integers to binary or hexadecimal?


Make sure you really know what you're asking. Integers are stored internally in binary, although for most purposes it is not incorrect to think of them as being in octal, decimal, or hexadecimal, whichever is convenient. The base in which a number is expressed matters only when that number is read in from or written out to the outside world.

In source code, a non-decimal base is indicated by a leading 0 or 0x (for octal or hexadecimal, respectively). During I/O, the base of a formatted number is controlled in the printf and scanf family of functions by the choice of format specifier (%d, %o, %x, etc.) and in the strtol and strtoul functions by the third argument. During binary I/O, however, the base again becomes immaterial.

For more information about ``binary'' I/O, see question 2.11. See also questions 8.6 and 13.1.

References: ANSI Secs. 4.10.1.5,4.10.1.6
ISO Secs. 7.10.1.5,7.10.1.6


Read sequentially: prev next up top


This page by Steve Summit // Copyright 1995 // mail feedback