LoginSignup
1
2

More than 5 years have passed since last update.

C > 10進数を16進数に変換 > sprintf()を使わない

Last updated at Posted at 2016-10-03

C言語にてsprintf()を使わないで10進数から16進数に変換する方法を検討。
マイコンにてメモリ制約が厳しい時にsprintf()を使わないという選択肢があるかもしれない。

code v0.1

#include <stdio.h>
#include <stdbool.h>

bool toHex1(int val, char *dstPtr){
    if (dstPtr == NULL) {
        return false;
    }
    sprintf(dstPtr, "%X", val);
    return true;
}
bool toHex2(int val, char *dstPtr) {
    if (dstPtr == NULL) {
        return false;
    }

    char wrkstr[5];
    static const int maxbit = 16;
    int wrkval = val;
    int bit = 0;
    while(bit <= maxbit) {
        wrkval = (val >> bit & 0xF);
        if (wrkval == 0) {
            break;
        }
        if (wrkval < 10) {
            wrkstr[bit/4] = '0' + wrkval;
        } else {
            wrkstr[bit/4] = 'A' + (wrkval - 10);
        }
//      printf("%d", wrkval);
        bit += 4;
    }

    int idx = bit / 4 - 1;
    while(idx >= 0) {
        dstPtr[idx] = wrkstr[bit / 4 - idx - 1];
        idx--;  
    }

    return true;        
}

int main(void) {
    int val=65534;
    char res[20];

    if(toHex1(val, res)) {
        printf("%d %s\n", val, res);
    }
    if(toHex2(val, res)) {
        printf("%d %s\n", val, res);
    }

    return 0;
}

結果
65534 FFFE
65534 FFFE

何か複雑なものになってしまた。

TODO: 値が0の時にミスってる。
http://ideone.com/94tjai

code v0.2 (改良版)

@shiracamus さんのコードが良いです。

1
2
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2