如何将负十进制数转换为带符号的八进制/十六进制数。
这是我的部分代码及其输出:
#include <stdio.h>
#include <float.h>
#include <limits.h>
int main()
{
signed short int sui1 = -127;
printf("+------------+-----+-----+------------+------------+------------+");
printf("------------+------------+\n");
printf("%s %11s %6s %5s %12s" , "Type", "Var", "Size", "Dec.", "Hex." );
printf("%13s %10s %14s", "Oct.", "FP", "Exp\n");
printf("%s %10s %4i %6i %#14x" , "char", "c1", sizeof(c1), c1, c1);
printf("%#13o %10f %22e\n", c1, c1, c1);
return 0;
}
我的八进制和十六进制的输出没有我希望的负数,有什么建议吗?
十进制= -128
八进制=0177601
十六进制=0xff81
最佳答案
让我们以8 位 中的二进制数为例来使事情更清楚:
11111111
如果它被认为是有符号数,则十进制值为-1
11111111
||||||||---> +1*2^0
|||||||----> +1*2^1
||||||-----> +1*2^2
|||||------> +1*2^3
||||-------> +1*2^4
|||--------> +1*2^5
||---------> +1*2^6
|----------> -1*2^7
-------
-1
因为最左边的位将被视为符号位并被视为负数,但其余(前 7 位)将始终保持正数,当按原样获取 base 10 中的值时如上所示
如果它是一个无符号位,则所有位都将为正数以得到以 10 为基数的值,即 255
11111111
||||||||---> +1*2^0
|||||||----> +1*2^1
||||||-----> +1*2^2
|||||------> +1*2^3
||||-------> +1*2^4
|||--------> +1*2^5
||---------> +1*2^6
|----------> +1*2^7
-------
255
如您所见,二进制数 11111111
在有符号和无符号的二进制表示法中是相同的(即使在八进制表示法 (0377
) 和十六进制表示法 (0xFF
)) 但十进制表示法不同,这取决于您将其视为有符号数还是无符号数
这是一个将有符号十进制转换为十六进制和八进制的程序
#include <stdio.h>
int main()
{
int nb;
printf("please enter the decimal number: ");
scanf("%d",&nb);
char octal[100]="",hex[100]="";
//octal will hold the octal notation
//hex will hold the hexadecimal notation
sprintf(octal,"%#o",nb); //convert decimal to octal
sprintf(hex,"%#X",nb); // convert decimal to hexadecimal
// show the result
printf("converting %d to hexadecimal notation %s\n",nb,hex);
printf("converting %d to octal notation %s\n",nb,octal);
return 0;
}
关于c - 标准 C 代码中的负整数/浮点十进制数到带符号的十六进制和八进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28014383/