[英]Convert Hexadecimal to Decimal in AVR Studio?
如何在AVR Studio中將十六進制(unsigned char類型)轉換為十進制(int類型)?
是否有可用的內置功能?
在AVR上,我在使用傳統的hex 2 int方法時遇到了問題:
char *z="82000001";
uint32_t x=0;
sscanf(z, "%8X", &x);
要么
x = strtol(z, 0, 16);
他們只提供錯誤的輸出,沒有時間調查原因。
因此,對於AVR微控制器,我編寫了以下函數,包括相關注釋以使其易於理解:
/**
* hex2int
* take a hex string and convert it to a 32bit number (max 8 hex digits)
*/
uint32_t hex2int(char *hex) {
uint32_t val = 0;
while (*hex) {
// get current character then increment
char byte = *hex++;
// transform hex character to the 4bit equivalent number, using the ascii table indexes
if (byte >= '0' && byte <= '9') byte = byte - '0';
else if (byte >= 'a' && byte <='f') byte = byte - 'a' + 10;
else if (byte >= 'A' && byte <='F') byte = byte - 'A' + 10;
// shift 4 to make space for new digit, and add the 4 bits of the new digit
val = (val << 4) | (byte & 0xF);
}
return val;
}
例:
char *z ="82ABC1EF";
uint32_t x = hex2int(z);
printf("Number is [%X]\n", x);
編輯:sscanf也適用於AVR,但對於大十六進制數字,你需要使用“%lX”,如下所示:
char *z="82000001";
uint32_t x=0;
sscanf(z, "%lX", &x);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.