SoFunction
Updated on 2025-04-18

C++ sample code for implementing binary conversion using printf statement

In C language,printfFunctions can directly implement partial-digit conversion function, and quickly output values ​​of different-digits through format specifiers. The following are detailed usage methods and example codes:

1. Printf natively supported primary conversion

1. Decimal, octal, hexadecimal conversion

#include <>
int main() {
    int num = 255;
    // Decimal output (default)    printf("Decimal: %d\n", num);  // 255
    // Octal output (no prefix)    printf("Octal: %o\n", num);  // 377
    // Hexadecimal output (lowercase letters)    printf("Hexadecimal: %x\n", num); // ff
    // Hexadecimal output (caps)    printf("Hexadecimal: %X\n", num); // FF
    return 0;
}

2. Display the prefix

#include <>
int main() {
    int num = 255;
    // Show octal prefix 0    printf("Octal with prefix: %#o\n", num); // 0377
    // Show hexadecimal prefix 0x/0X    printf("Prefixed hexadecimal: %#x\n", num); // 0xff
    printf("Prefixed hexadecimal: %#X\n", num); // 0XFF
    return 0;
}

3. Specify output width and fill

#include <>
int main() {
    int num = 15;
    // Output 8-bit width, the preamble zero is filled in part    printf("Eggregation of zero: %#08o\n", num);  // 0000017
    printf("Hexadecimal with zeros: %#08x\n", num); // 0x00000f
    return 0;
}

2. Printf does not support the binary conversion

1. Binary output (need to be manually implemented)

#include <>
void print_binary(unsigned int num) {
    if (num > 1) print_binary(num >> 1);
    putchar((num & 1) ? '1' : '0');
}
int main() {
    int num = 10;
    printf("Binary: ");
    print_binary(num); // 1010
    return 0;
}

2. Arbitrary Category Conversion (General Method)

#include <>
#include <>
void reverse(char* str) {
    int len = strlen(str);
    for (int i = 0; i < len/2; i++) {
        char temp = str[i];
        str[i] = str[len-1 - i];
        str[len-1 - i] = temp;
    }
}
void dec_to_base(unsigned int num, int base, char* output) {
    if (base < 2 || base > 36) {
        strcpy(output, "Invalid base");
        return;
    }
    const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int index = 0;
    do {
        output[index++] = digits[num % base];
        num /= base;
    } while (num > 0);
    output[index] = '\0';
    reverse(output);
}
int main() {
    char buffer[32];
    dec_to_base(255, 2, buffer);
    printf("Binary: %s\n", buffer); // 11111111
    return 0;
}

3. Enter the values ​​of other digits (usage of scanf)

#include <>
int main() {
    int num;
    // Enter a hexadecimal number (such as FF)    printf("Enter hexadecimal number: ");
    scanf("%x", &num);
    printf("Decimal value: %d\n", num); // 255
    // Enter an octal number (such as 377)    printf("Enter octal number: ");
    scanf("%o", &num);
    printf("Decimal value: %d\n", num); // 255
    return 0;
}

4. Things to note

Type Limitations

use%o, %x, %XWhen it is recommended to useunsignedType, avoid symbol extension issues:

unsigned int num = 255;
printf("%#x\n", num); // Correct output 0xff

Binary output optimization

// Use macros to define fast output binary#define PRINT_BINARY(n) \
    for (int i = sizeof(n)*8-1; i >= 0; i--) \
        putchar((n & (1 << i)) ? '1' : '0'); \
    putchar('\n')
int main() {
    PRINT_BINARY(10); // 00000000000000000000000000001010
    return 0;
}

Large number processing

  • For more thanunsigned intRange values ​​need to be processed using strings (similar to Pythonint(string, base))。

passprintfIt can directly implement octal and hexadecimal output, and binary and other binary systems need to be implemented manually. If more complex phase conversion is needed (such as floating-point conversion or super-large number processing), it is necessary to combine string operations or mathematical library functions.

This is the article about C++'s sample code for using printf statement to implement binary conversion. For more related C++ binary conversion content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!