| CSC373/406: Integers: Bits! How Programs are Stored [6/9] | ![]() ![]() ![]() |
Storing programming statements
Storing data
int: 32-bit binary numberlong: 32-bit or 64-bit binary number (depends on the
machine)double: we'll discuss its format next weekchar: ASCII encoding (or Unicode, which is an extension)Using printf format strings to look at underlying
representations of data
#include <stdio.h>
int main( ) {
int a = 28;
double b = 33333.555555;
char c = 'c';
printf("a: %d %x\nb: %4.1f %x\nc: %d %x\n",
a, a, b, b, (int) c, c);
}
Conversion between decimal, binary, and hex
In base 10, the nth digit from the right in the number represents the number of 10^n 's in the number
Example: 2538
| Digit | Offset from the right | Represents |
|---|---|---|
| 8 | 0 | 8 * 10^0 = 8 |
| 3 | 1 | 3 * 10^1 = 30 |
| 5 | 2 | 5 * 10^2 = 500 |
| 8 | 0 | 2 * 10^3 = 2000 |
So the number is 8 + 30 + 500 + 2000 = 2538.
Converting from other bases to base 10 can be done in the same way. For example, in binary, each column represents a power of 2.
Example: 1001101
| Digit | Offset from the right | Represents |
|---|---|---|
| 1 | 0 | 1 * 2^0 = 1 |
| 0 | 1 | 0 * 2^1 = 0 |
| 1 | 2 | 1 * 2^2 = 4 |
| 1 | 3 | 1 * 2^3 = 8 |
| 0 | 4 | 0 * 2^4 = 0 |
| 0 | 5 | 0 * 2^5 = 0 |
| 1 | 6 | 1 * 2^6 = 64 |
So the number is 1 + 0 + 4 + 8 + 0 + 0 + 64 = 37
Example of conversion from hex
Example: 0xA203
| Digit | Offset from the right | Represents |
|---|---|---|
| 3 | 0 | 3 * 16^0 = 3 |
| 0 | 1 | 0 * 16^1 = 0 |
| 2 | 2 | 0 * 16^2 = 512 |
| a | 3 | 10 * 16^3 = 40960 |
So the number is 3 + 0 + 512 + 40960 = 41475