Number Bases and Conversion
Part of: Data
Beyond Binary and Decimal. A number base (or radix) tells you how many distinct digits a system uses and what each place is worth. Decimal is base 10 (digits 0-9). Binary is base 2 (digits 0-1). Computing also uses hexadecimal , base 16, which has digits 0-9 plus the letters A-F representing values 10 through 15. Hexadecimal is popular because it is a compact shorthand for binary: each hex digit corresponds to exactly four bits. So the byte 11111111 becomes just FF, and 1010 becomes A. Place Value in Any Base. The rule is the same in every base: each place is a power of the base. In base 16 the places are 1, 16, 256, and so on: - Hex 2A = 2 16 + 10 = 42 in decimal. - Hex FF = 15 16 + 15 = 255 . Converting Decimal to Another Base. To convert a decimal number to base b , repeatedly divide by b and collect the remainders, reading them in reverse. Here is decimal-to-binary using that method: The remainders (n % 2) are the binary digits from least significant to most significant, so we reverse them at the end. What usually goes wrong. What you see What caused it How to fix it --- --- --- The digits come out backwards, so 11 prints as 1101 the remainders were joined in the order they app
Challenge: Decimal to Binary