Number bases

Basic types / Numbers / Integer

//decimal number system
int decimal = 42;

//octal number system
int octal = 042;
//octal is 34

//hexadecimal number system
int hexadecimal = 0x42;
//hexadecimal is 66

//binary number system (standard since C23)
int binary = 0b1010;
//binary is 10

//42 to decimal string
char sDecimal[16];
snprintf(sDecimal, sizeof sDecimal, "%d", 42);
//sDecimal is "42"

//42 to octal string
char sOctal[16];
snprintf(sOctal, sizeof sOctal, "%o", 42);
//sOctal is "52"

//42 to hexadecimal string
char sHexadecimal[16];
snprintf(sHexadecimal, sizeof sHexadecimal, "%x", 42);
//sHexadecimal is "2a"

//42 to binary string: bit by bit, from the highest
//(C23 adds %b to printf, but not every library has it yet)
char sBinary[9];
for (int i = 0; i < 8; i++) {
    sBinary[i] = (42 >> (7 - i)) & 1 ? '1' : '0';
}
sBinary[8] = '\0';
//sBinary is "00101010"

//and back from a string in any base
long fromBinary = strtol("101010", nullptr, 2);
//fromBinary is 42
long fromHexadecimal = strtol("2a", nullptr, 16);
//fromHexadecimal is 42

printf("decimal is %d\n", decimal);
printf("octal is %d\n", octal);
printf("hexadecimal is %d\n", hexadecimal);
printf("binary is %d\n", binary);
printf("sDecimal is %s\n", sDecimal);
printf("sOctal is %s\n", sOctal);
printf("sHexadecimal is %s\n", sHexadecimal);
printf("sBinary is %s\n", sBinary);
printf("fromBinary is %ld\n", fromBinary);
printf("fromHexadecimal is %ld\n", fromHexadecimal);