原文: https://www.programiz.com/c-programming/examples/octal-binary-convert
在此示例中,您将学习通过创建用户定义的函数来将二进制数手动转换为八进制,反之亦然。
要理解此示例,您应该了解以下 C 编程主题:
将二进制转换为八进制的程序
在此程序中,我们将首先将二进制数字转换为十进制。 然后,十进制数字转换为八进制。
#include <math.h>#include <stdio.h>int convert(long long bin);int main() {long long bin;printf("Enter a binary number: ");scanf("%lld", &bin);printf("%lld in binary = %d in octal", bin, convert(bin));return 0;}int convert(long long bin) {int oct = 0, dec = 0, i = 0;// converting binary to decimalwhile (bin != 0) {dec += (bin % 10) * pow(2, i);++i;bin /= 10;}i = 1;// converting to decimal to octalwhile (dec != 0) {oct += (dec % 8) * i;dec /= 8;i *= 10;}return oct;}
输出
Enter a binary number: 101001101001 in binary = 51 in octal
将八进制转换为二进制的程序
在此程序中,八进制数首先会转换为十进制。 然后,将十进制数转换为二进制数。
#include <math.h>#include <stdio.h>long long convert(int oct);int main() {int oct;printf("Enter an octal number: ");scanf("%d", &oct);printf("%d in octal = %lld in binary", oct, convert(oct));return 0;}long long convert(int oct) {int dec = 0, i = 0;long long bin = 0;// converting octal to decimalwhile (oct != 0) {dec += (oct % 10) * pow(8, i);++i;oct /= 10;}i = 1;// converting decimal to binarywhile (dec != 0) {bin += (dec % 2) * i;dec /= 2;i *= 10;}return bin;}
输出
Enter an octal number: 6767 in octal = 110111 in binary
