如何将字符串转换为int32为十六进制并存储到缓冲区中

时间:2017-11-06 10:49:37

标签: c

我正在尝试将字符串转换为字符串然后转换为十六进制。字符串值表示例如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

2 个答案:

答案 0 :(得分:2)

你的问题似乎是一个基本的误解,一个数字可以存储&#34;作为十六进制&#34;。计算机始终以二进制形式存储数字。

以十六进制显示数字非常方便,因为一组四个二进制数字(位)与一个十六进制数字(0 - f)完全匹配。

但如果您希望计算机在屏幕上显示十六进制数字,唯一的方法是将这些数字编码为字符。在典型的基于ASCII的实现中,每个字符需要8个(!)位。

当您读取数字266时,存储在uint32_t的低16位的内容是

0000 0001 0000 1010
   0    1    0    a     (mapping to hex)

如果您要显示,则需要字符 01a, ASCII为30 (0011 0000)31 (0011 0001)61 (0110 0001)。具有printf()格式说明符的%x函数系列执行此转换。这给你

   3    0 |    3    1 |    3    0 |    6    1      (mapping to hex)
0011 0000 | 0011 0001 | 0011 0000 | 0110 0001      (four `char`)

现在问题中的代码会获取此字符串的各个字节(解释为数字!)并再次转换为十六进制字符串!

答案 1 :(得分:0)

如果使用标准库函数,则从具有十进制数的字符串转换为具有十六进制数的字符串是相当简单的。只需从程序中删除大部分代码,您最终会得到:

#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()。