![](/img/trans.png)
[英]Convert 20 Byte Hex (char string) to 10 Byte Binary Char String in C
[英]extracting the 4 byte of char from char string and convert the first 4 byte to integer in c
我有一個字符串,例如char *x = "1234 is a test";
其中前 4 個字符是我需要提取為整數的十六進制數字。
我的方法是提取前 4 個字符:
char dest[5];
strncpy(dest, x,4);
char dest[5]='\0';
如何將這個 4-char 字符串轉換為int
?
我試過使用strtol(dest, &ptr,16 );
,但strtol
查找並轉換數值。
該字符串似乎是從網絡獲得的; 因此不使用strtol
,我想使用十六進制到十進制的轉換。 我需要先將 4 個字符打包成一個int
類型並使用它。
如何將這 4 個字符合並為int
?
char *x = "1234 is a test";
根據您是否可以依賴不是十六進制數字的第五個字符,您可以跳過復制,並將strtol()
直接瞄准x
。 它將在您選擇的基數中不是有效數字的第一個字符處停止解析。
如果您不能依賴它,那么您的復制代碼需要進行一些清理: char dest[5]
聲明一個包含五個元素的數組,索引為0到4 ,因此dest[5] = '\\0';
將不存在的第六個元素設置為零,導致未定義的行為。 復制后,數字將駐留在dest[0]
到dest[3]
,因此您確實希望將dest[4]
歸零。
並將char
放入char dest[4] = '\\0';
, 否則你正在重新聲明dest
...
char dest[5];
strncpy( dest, x, 4 );
dest[4] = '\0';
更優雅的將是:
char dest[5] = { 0 }; // actually sets *all* elements to zero
memcpy( dest, x, 4 );
我試過使用 strtol(dest, &ptr,16 );
那應該有效,真的。 你沒有顯示代碼; 根據您對strtol()
“找到數值並分離”的評論,我假設您有點困惑,並查看了ptr
的結果。 那只是一個指向strtol()
停止解析的指針。 結果由strtol()
返回:
char * ptr;
int i = strtol( dest, &ptr, 16 );
如果您對結束指針不感興趣,您可以只傳遞NULL
:
int i = strtol( dest, NULL, 16 );
事實上,如果前 4 個字節根本不是十六進制數字,而是一個int
的二進制表示(您在后面編輯的最后一段似乎暗示了這一點),那么處理它的方法將是union
。
union
{
int ival;
char cval[4];
} convert;
memcpy( &convert.cval, x, 4 );
int i = convert.ival;
這是當然的,假設sizeof( int ) == 4
和接收器具有相同的字節順序(字節順序)作為發件人。如果沒有,你就麻煩了, unions
是棘手的方式。
假設第一個字節是最高有效字節:
int convert_char(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
else if (c >= 'A' && c <= 'F') {
return (10 + c - 'A');
}
else if (c >= 'a' && c <= 'f') {
return (10 + c - 'a');
}
return 0;
}
char *x = "1234 is a test";
int y = 0;
y = convert_char(x[0]) * 16 * 16 * 16 + convert_char(x[1]) * 16 * 16 + convert_char(x[2]) * 16 + convert_char(x[3]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.