簡體   English   中英

負整數/浮點十進制數,以標准C代碼中的有符號十六進制和八進制表示

[英]negative integer/float decimal number to signed hex and octal in standard C code

如何將負的十進制數字轉換為帶符號的八進制/十六進制數字。

這是我的代碼及其輸出的一部分:

#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位)在以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;
}

"%o""%x"格式說明符期望unsigned匹配的參數。 因此,即使代碼通過帶負號的帶signed short int ,該值最終也會在打印之前轉換為unsigned 因此,僅打印正值(和0)。

要在base-16(或base-8帶有"%o" )中打印一個負數,可以使用代碼。

signed short int sui1 = -127;
printf("%c%x", sui1 < 0 ? '-' : '+', (unsigned) abs(sui1));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM