簡體   English   中英

將2位小數轉換為十六進制

[英]Converting 2-Digit Decimal to Hexadecimal

我是一名初學者-中級Arduino編碼器,試圖將我的一個項目的2位十進制轉換為十六進制。 我編寫的代碼似乎可以正常工作,但是看起來比預期的要長得多:

int decToHex(int ones, int tens) {
  int result = 0x00;
  if (tens == 0) {
    switch (ones) {
      case 0:
        result = 0x00;
        break;
      case 1:
        ...
      case 9:
        result = 0x09;
        break;
    }
  } else {
    switch (tens) {
      case 1:
        switch (ones) {
          case 0:
            result = 0x0A;
            break;
          case 1:
            ...
          case 9:
            result = 0x13;
            break;
        }
        break;
      case 2:
        ...
      case 9:
        switch (ones) {
          ...
        }
        break;

    }
  }
  return result;
}

縮短此代碼的任何幫助將不勝感激。

輸入2位數十進制值的簡便方法

並將其輸出為十六進制值。

unsigned int inputValue = 0;

if( 1 == scanf( "%u", &inputValue ) )
{
    if( 99 >= inputValue )
    {
        printf( %04x\n", inputValue );
    }

    else
    {
         // handle range error
    }
}

else
{
    // handle scanf() failure
}

對於發布的功能:

char * decToHex(unsigned int ones, unsigned int tens) 
{
    short int result = 0x0000;
    char *hexStr = NULL;

    if( NULL != (hexStr = malloc(7) ) )
    {
        // handle error and exit
    }

    // implied else, malloc successful

    unsigned short int totalValue = ones+ (10*tens);

    sprintf( hexStr, "0X%04x", totalValue );

    return hexStr;
}

把事情簡單化。 您想要將Int的十六進制表示形式打印為字符串嗎? 見下文。 除了以10為基數或以16為基數的表示形式,沒有其他區別。 可以不同地打印。

int a = 10 * tens + ones;

printf("%x\n", a);
printf("0x%x\n", a);

暫無
暫無

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

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