[英]How to convert string to int32 to hex and store into buffer
我正在嘗試將字符串轉換為字符串,然后轉換為十六進制。 字符串值表示例如266之類的整數。執行此操作的主要原因是,我將所有值存儲在字符串中,並希望通過網絡將其發送到主機,因此,我必須將所有值表示為十六進制。 如果我將字符串“ 266
”轉換為int32,然后轉換為十六進制“ 0x010a
”並將十六進制值存儲在緩沖區中,則該緩沖區包含“ 30 31
”而不是0x010a。 這是我的問題的運行示例。
#include <stdio.h> /* printf */
#include <stdint.h> /* int32_t*/
#include <stdlib.h> /* strtol, malloc */
#include <string.h> /* memcpy */
int integer_to_hex(
char **out_hex,
int *out_len,
int32_t value)
{
*out_len = 0;
*out_hex = NULL;
if ( value < 128 && value > -128)
{
*out_len = 1;
*out_hex = malloc(*out_len);
sprintf(*out_hex,"%02x", value & 0xff);
return 0;
}
else if (value < 32767 && value > -32767)
{
*out_len = 2;
*out_hex = malloc(*out_len);
sprintf(*out_hex,"%04x", value);
return 0;
}
return -1;
}
int main()
{
char *value_str = "266";
int32_t val_int = strtol(value_str,NULL,10);
char *out_hex;
int out_len;
int ret_val = integer_to_hex(&out_hex, &out_len, val_int);
printf("ret_val=%d\n", ret_val);
printf("out=%s\n", out_hex);
printf("out_len=%d\n", out_len);
char *buffer = malloc(out_len);
memcpy(&buffer, &out_hex, out_len);
int i;
for(i=0;i<out_len;i++)
printf("buffer=%02x\n", buffer[i]);
return 0;
}
輸出:
ret_val=0
out=010a
out_len=2
buffer=30
buffer=31
您的問題似乎是一個根本性的誤解,認為數字可以“十六進制”存儲。 計算機始終以二進制形式存儲數字。
用十六進制顯示數字很方便,因為一組四個二進制數字(位)與一個單個十六進制數字( 0
- f
)完全匹配。
但是,如果您希望計算機在屏幕上顯示十六進制數字,則唯一的方法是將這些數字編碼為字符。 在典型的基於ASCII的實現中,每個字符占用八(!)位。
當您讀取數字266時,存儲在uint32_t
低16位中的是
0000 0001 0000 1010
0 1 0 a (mapping to hex)
如果要顯示這一點,需要字符 0
, 1
和a
,其在ASCII編碼為30 (0011 0000)
31 (0011 0001)
和61 (0110 0001)
具有%x
格式說明符的printf()
系列函數執行此轉換。 這給你
3 0 | 3 1 | 3 0 | 6 1 (mapping to hex)
0011 0000 | 0011 0001 | 0011 0000 | 0110 0001 (four `char`)
現在,您問題中的代碼將使用此字符串的各個字節(解釋為數字!),然后再次轉換為十六進制字符串!
如果使用標准庫函數,則從具有十進制數字的字符串轉換為具有十六進制數字的字符串是相當簡單的。 只需從程序中剝離大部分代碼,您將得到以下結果:
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#define LARGE_ENOUGH (8+1)
int main (void)
{
const char str_dec[] = "266";
char str_hex [LARGE_ENOUGH];
int32_t binary = strtol(str_dec, NULL, 10);
sprintf(str_hex, "%.4"PRIX32, binary);
puts(str_hex);
}
沒有明顯的理由需要使用malloc()。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.