Skip to content

Instantly share code, notes, and snippets.

@kamiyaowl kamiyaowl/main.c
Created Jun 21, 2015

Embed
What would you like to do?
Number -> Hex for Embedded
#include <stdio.h>
typedef unsigned short uint16;
typedef unsigned char uint8;
const char numberTable[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
void itoa(uint16 src, char* buf){
uint8 i;
buf[0] = '0';
buf[1] = 'x';
for (i = 0; i < 4; ++i){
buf[2 + i] = numberTable[(src >> ((3 - i) << 2)) & 0xf];
}
}
int main(void) {
char buf[6];
for (int i = 0; i <= 0xffff; ++i){
printf("%d -> ", i);
//TEST
itoa(i, buf);
for (int k = 0; k < 6; ++k){
putchar(buf[k]);
}
putchar('\r');
putchar('\n');
}
return 0;
}
@kamiyaowl

This comment has been minimized.

Copy link
Owner Author

commented Jun 21, 2015

(3 - i)

桁数[3,2,1,0]

((3 - i) << 2)

シフト数生成( << 2 == * 4) [12,8,4,0 ]

src >> ((3 - i) << 2)

シフト0xabcd -> [0x000a, 0x00ab, 0x0abc, 0xabcd]

(src >> ((3 - i) << 2)) & 0xf

最下位桁マスク [0xa, 0xb, 0xc, 0xd]

 numberTable[(src >> ((3 - i) << 2)) & 0xf]

0~15をcharテーブルから持ってくる

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.