STM32 在keil下進行strtol函數的功能測試
源碼:
void test_str2num_strtol(void)
{
int a;
printf("\r\n\r\n0x1234 = %d,",strtol("0x1234",NULL,0));
printf("\r\n1234 = %d,",strtol("1234",NULL,0));
printf("\r\nHex:1234 = %d,",strtol("1234",NULL,16));
printf("\r\n0 = %d,",strtol("0",NULL,0));
printf("\r\n01234 = %d,",strtol("01234",NULL,0));
printf("\r\n0.1234 = %d,",strtol("0.1234",NULL,0));
printf("\r\n-1234 = %d,",strtol("-1234",NULL,0));
printf("\r\n1234ab = %d,",strtol("1234ab",NULL,0));
printf("\r\n0b1011 = %d,",strtol("0b1011",NULL,0));
printf("\r\nbin:0b1011 = %d,",strtol("0b1011",NULL,2));
printf("\r\nbin:1011 = %d,",strtol("1011",NULL,2));
printf("\r\n0xB = %d,",strtol("0xB",NULL,0));
printf("\r\nabc1234 = %d,\r\n",strtol("abc1234",NULL,0));
}
輸出:
0x1234 = 4660,
1234 = 1234,
Hex:1234 = 4660,
0 = 0,
01234 = 668,
0.1234 = 0,
-1234 = -1234,
1234ab = 1234,
0b1011 = 0,
bin:0b1011 = 0,
bin:1011 = 11,
0xB = 11,
abc1234 = 0,
可以看出,這個函數:
如果最後一個參數設置爲0的話,會默認把字符串當作10進制進行轉換;
如果0x開頭,則以16進制轉換;
如果以0開頭,則以8進制進行轉換;
如果最後一個參數爲 2 的話,那麼就會以二進制轉換;
如果是16則以16進制進行轉換。
出錯,就返回0.
如果以其他字符開頭,則以出錯返回0.
如果後面有不可識別的字符,則只轉換前面的數字。