我希望用戶在格式輸入MAC地址:aa:bb:cc:dd:ee:ff
,然後我把這個在我的代碼argv[1]
例如。獲取用戶輸入並將其存儲在十六進制
現在我該如何將它存儲在十六進制格式的數組中?
我需要的是該數組看起來像這樣:
char temp[6] = { 0xaa,0xbb,0xcc,0xdd,0xee,0xff }
任何想法?
我希望用戶在格式輸入MAC地址:aa:bb:cc:dd:ee:ff
,然後我把這個在我的代碼argv[1]
例如。獲取用戶輸入並將其存儲在十六進制
現在我該如何將它存儲在十六進制格式的數組中?
我需要的是該數組看起來像這樣:
char temp[6] = { 0xaa,0xbb,0xcc,0xdd,0xee,0xff }
任何想法?
int a, b, c, d, e, f;
sscanf(argv[1], "%x:%x:%x:%x", &a, &b, &c, &d, &e, &f);
使用INT得到的值,那麼你可以將它們放在字符數組,因爲他們有一個字節的值。
工作。我之前使用sscanf,但沒有將值存儲爲整數。非常感謝。 – cocoacoder 2012-03-28 22:03:17
sscanf(str, "%x:%x:%x:%x:%x:%x", &temp[0], &temp[1], &temp[2], &temp[3], &temp[4], &temp[5]);
這可能會溢出內存,因爲%x需要一個整數。 – 2012-03-28 21:43:18
在這種情況下,temp必須是一個int向量 – rbelli 2012-03-28 21:44:18
數組未存儲爲十六進制格式;十六進制格式僅適用於閱讀和打印。在內部,所有數字都以二進制形式存儲。
要讀取十六進制數字,您可以使用scanf
,並打印十六進制數字,您可以使用printf
。要讓scanf
知道您希望它讀取十六進制數字,請使用格式說明符%x
。如果你想讀取char
而不是int, use the modifier
hh`。下面是你如何使用它爲你的情況的一個例子:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
unsigned char addr[6];
char dummy;
if (argc != 2) {
fprintf(stderr, "Wrong number of arguments\nUsage: %s ADDRESS\n",
argv[0]);
exit(1);
}
int res = sscanf(argv[1], "%2hhx:%2hhx:%2hhx:%2hhx:%2hhx:%2hhx%c",
&addr[0], &addr[1], &addr[2], &addr[3], &addr[4], &addr[5],
&dummy);
if (res == EOF) {
fprintf(stderr, "Reached end of input without matching\n");
exit(1);
} else if (res < 6) {
fprintf(stderr, "Got fewer hex digits than expected\n");
exit(1);
} else if (res > 6) {
fprintf(stderr, "Got extra characters after input\n");
exit(1);
}
printf("Got: %02hhx, %02hhx, %02hhx, %02hhx, %02hhx, %02hhx\n",
addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
return 0;
}
注意,我在一個虛擬的字符輸入後讀取,檢查包含垃圾在最後輸入。這可能或可能不是您的用例所必需的。
您是否閱讀過文檔'sscanf'? – 2012-03-28 21:37:31
你可以使用sscanf來做到這一點。 – rbelli 2012-03-28 21:38:49