c - 标准 C 代码中的负整数/浮点十进制数到带符号的十六进制和八进制

标签 c hex decimal signed octal

如何将负十进制数转换为带符号的八进制/十六进制数。

这是我的部分代码及其输出:

#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/

相关文章:

c - 透明的 SQLite 数据压缩

c - 获取程序传输的总 MPI 字节数

c++ - OpenMP,for 循环内部部分

c - 在C中显示 float 的小数位

java - 股票价格的 BigDecimal?

c++ - 优化 SphereInFrustrum 检查

powershell - 通过 Powershell 十六进制编辑二进制文件的方法

包含十六进制的字符串中的 python2 与 python3

javascript - 十六进制颜色代码的按位求补能否始终返回 6 个字符?

c# - 在 C# 中使用 System.Decimal 进行数学运算