1. Use C++ standard library functions
1. To any decimal
#include <string> #include <iostream>int main() { std::string num = "1A3F"; // Hexadecimal number int decimal = stoi(num, nullptr, 16); // The third parameter specifies the original binary std::cout << decimal; // Output: 6719}
2. Decimal to other binary
#include <bitset> #include <iostream> int main() { int num = 255; // Turn to binary (8 bits) std::cout << std::bitset<8>(num) << "\n"; // 11111111 // Turn to hexadecimal (lower case) std::cout << std::hex << num << "\n"; // ff // Turn to octal std::cout << std::oct << num; // 377 }
2. Custom conversion function (supports any 2-36-bit)
1. Decimal to any division
#include <algorithm> #include <string> std::string dec_to_base(int num, int base) { if (base < 2 || base > 36) return ""; std::string result; const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; while (num > 0) { result += digits[num % base]; num /= base; } if (()) return "0"; std::reverse((), ()); return result; } // Example:dec_to_base(255, 16) return "FF"
2. To any decimal
#include <cctype> #include <string> int base_to_dec(std::string num, int base) { if (base < 2 || base > 36) return -1; int result = 0; for (char c : num) { int value = isdigit(c) ? c - '0' : toupper(c) - 'A' + 10; if (value >= base) return -1; // Illegal input result = result * base + value; } return result; } // Example:base_to_dec("FF", 16) return 255
3. Complete sample code
#include <iostream> #include <algorithm> #include <string> using namespace std; // Decimal to any binary (2-36)string dec_to_base(int num, int base) { if (base < 2 || base > 36) return "Invalid base"; string result; const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; do { result += digits[num % base]; num /= base; } while (num > 0); reverse((), ()); return () ? "0" : result; } // Any Category to Decimal (2-36)int base_to_dec(string num, int base) { if (base < 2 || base > 36) return -1; int result = 0; for (char c : num) { int value = isdigit(c) ? c - '0' : toupper(c) - 'A' + 10; if (value >= base) return -1; result = result * base + value; } return result; } int main() { // Decimal 255 to hexadecimal cout << dec_to_base(255, 16) << endl; // Output FF // Binary 11111111111 to decimal cout << base_to_dec("11111111", 2) << endl; // Output 255 // Hexadecimal conversion example cout << dec_to_base(1234, 36) << endl; // Output YA cout << base_to_dec("YA", 36) << endl; // Output 1234 return 0; }
4. Things to note
Validity check: You need to verify whether the input value is legal (such as binary cannot contain 2-9)
Case processing: Custom functions handle uppercase letters by default, and can be modified toupper() to lowercase.
Negative number processing: The sample code does not process negative numbers, and symbol processing can be added if needed
Large numbers support: For values that exceed the int range, it is recommended to use string processing or long long type
If you need to deal with super large numbers (more than long long range), you need to use a string to perform bit-by-bit calculation algorithm. Here are the most commonly used basic implementation methods.
5. Method supplement
Use the printf statement to implement the binary conversion
In C language, the printf function 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:
When using %o, %x, %X, it is recommended to use the unsigned type to avoid symbolic expansion problems:
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 values that exceed the unsigned int range, string processing is required (similar to Python's int(string, base)).
Printf 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.
The above is the detailed content of the implementation method of C++ tutorial on the basis of the C++ primary conversion. For more information about C++ primary conversion, please pay attention to my other related articles!