【问题标题】:Get the RGB-hexadecimal values from an array and give it to an malloc-array as int从数组中获取 RGB 十六进制值并将其作为 int 提供给 malloc 数组
【发布时间】:2018-05-18 06:24:40
【问题描述】:

我需要一个方法,我如何从数组中获取一个十六进制数,然后将它提供给一个 int 类型的变量。我知道这听起来很容易,但我需要以“特殊方式” - 例如:

我给出了一个 RGB 十六进制颜色:01a7ff - 我将 R、G 和 B 的值保存在额外的数组中 - 如下所示:

char red[3];
red[0] = '0';
red[1] = '1';
red[2] = '\0';

char green[3];
green[0] = 'a';
green[1] = '7';
green[2] = '\0';

char blue[3];
blue[0] = 'f';
blue[1] = 'f';
blue[2] = '\0';

现在我想将完整的红色、绿色和蓝色数组提供给 malloc 保留数组,如下所示:

char *data;
data = malloc(sizeof(char)*6);

data[0] = 01; //red array
data[1] = a7; //green array
data[2] = ff; //blue array

我第一次尝试使用 atoi(),但如果数组也有十六进制文字 (a,b,c,d,e,f),那将不起作用 - 有没有人为我提供解决方案?

干杯

【问题讨论】:

  • man strtoul 会有所帮助。
  • 我尝试使用strtol,但我一直在这样做,然后将十六进制转换为十进制数。man strtoul 不同吗?
  • 那你想要什么?把它们放在 char 数组中?
  • 看起来像是对数据表示的基本误解。
  • 我希望将存储在数组中的十六进制数字(例如绿色 a7)作为 a7 复制到数据 [1] - 所以我想要:data[1] = green;

标签: c arrays hex rgb atoi


【解决方案1】:

如果数据包含 unsigned char 值,则应该这样做:

data[0] = (unsigned char) strtol(red, NULL, 16);
data[1] = (unsigned char) strtol(green, NULL, 16);
data[2] = (unsigned char) strtol(blue, NULL, 16);

注意:使用 unsigned char 来保存 0 到 255 之间的数据值就足够了

【讨论】:

  • 谢谢!这正是我想要的——现在我明白了。 :)
  • 请注意,OP char *data 可能会导致 data[1] = strtol(green, NULL, 16);data[2] = strtol(blue, NULL, 16); 出现意外结果
  • @DavidBowling 你是对的!我添加了对数据类型的说明。
  • 这是真的,我理解的常规 char 数据类型接受值 -127 到 127。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-03
  • 2014-02-18
  • 1970-01-01
  • 2018-03-20
  • 2018-02-24
  • 2021-08-08
  • 2018-07-27
相关资源
最近更新 更多