1、八进制转换成二进制
#include <math.h>
#include <stdio.h>
long octalToBinary(int octalnum)
{
int decimalnum = 0, i = 0;
long binarynum = 0;
while (octalnum != 0)
{
decimalnum = decimalnum + (octalnum % 10) * pow(8, i);
i++;
octalnum = octalnum / 10;
}
i = 1;
while (decimalnum != 0)
{
binarynum = binarynum + (long)(decimalnum % 2) * i;
decimalnum = decimalnum / 2;
i = i * 10;
}
return binarynum;
}
int main()
{
int octalnum;
printf("Enter an octal number: ");
scanf("%d", &octalnum);
printf("Equivalent binary number is: %ld", octalToBinary(octalnum));
return 0;
}
测试结果:
Enter an octal number: 100
Equivalent binary number is: 1000000
2、八进制转换成十进制
#include <math.h>
#include <stdio.h>
int convertValue(int num, int i) { return num * pow(8, i); }
long long toDecimal(int octal_value)
{
int decimal_value = 0, i = 0;
while (octal_value)
{
decimal_value += convertValue(octal_value % 10, i++);
octal_value /= 10;
}
return decimal_value;
}
int main()
{
printf("Enter octal value: ");
int octal_value;
scanf("%d", &octal_value);
long long result = toDecimal(octal_value);
printf("%d in decimal is %lld\n", octal_value, result);
return 0;
}
测试结果:
Enter octal value: 100
100 in decimal is 64
3、八进制转换成十六进制
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if 0
long octalToDecimal(long octalValue)
{
long decimalValue = 0;
int i = 0;
while (octalValue)
{
decimalValue += (long)(octalValue % 10) * pow(8, i++);
octalValue /= 10;
}
return decimalValue;
}
#endif
char *octalToHexadecimal(long octalValue)
{
char *hexadecimalValue = malloc(256 * sizeof(char));
sprintf(hexadecimalValue, "%lX", octalToDecimal(octalValue));
return hexadecimalValue;
}
static void test()
{
assert(strcmp(octalToHexadecimal(213), "8B") == 0);
assert(strcmp(octalToHexadecimal(174), "7C") == 0);
}
int main()
{
test();
int octalValue;
printf("Enter an octal number: ");
scanf("%d", &octalValue);
char *hexadecimalValue = octalToHexadecimal(octalValue);
printf("Equivalent hexadecimal number is: %s", hexadecimalValue);
free(hexadecimalValue);
return 0;
}
测试结果:
Enter an octal number: 100
Equivalent hexadecimal number is: 40
【欢迎关注编码小哥,学习更多实用的编程方法】