将未签名的char *(uint8_t *)转换为const char * [英] cast unsigned char * (uint8_t *) to const char *
问题描述
我有一个使用uint8_t *参数的函数:
I've a function which take an uint8_t * argument :
uint8_t* ihex_decode(uint8_t *in, size_t len, uint8_t *out)
{
uint8_t i, hn, ln;
for (i = 0; i < len; i+=2) {
hn = in[i] > '9' ? (in[i]|32) - 'a' + 10 : in[i] - '0';
ln = in[i+1] > '9' ? (in[i+1]|32) - 'a' + 10 : in[i+1] - '0';
out[i/2] = (hn << 4 ) | ln;
}
return out;
}
我将此功能与:
uint8_t data[SPM_PAGESIZE]; // SPM_PAGESIZE = 256 bytes
uint8_t sysex_data[SPM_PAGESIZE/2];
ihex_decode(data, strlen(data), sysex_data);
但是在这种情况下,我的编译器(avr-gcc)返回警告:
But in this case, my compiler (avr-gcc) return a warning :
main.c | 89 |警告:传递 strlen的参数1的指针目标的签名不同
/usr/include/string.h | 399 |注:预期为'const char *',但参数的类型为'uint8_t *'
main.c|89|warning: pointer targets in passing argument 1 of 'strlen' differ in signedness /usr/include/string.h|399|note: expected 'const char *' but argument is of type 'uint8_t *'
因此,我发现了通过类型转换数据var的解决方案:
So, i've found a solution by type casting the data var :
ihex_decode(data, strlen((const char *)data), sysex_data);
警告消失了,但我想知道这种解决方案是否安全。
The warning disappears but I wonder if this solution is safe.
有更好的方法吗?
谢谢
推荐答案
这很安全。该错误与将8位无符号整数与字符混合在一起,如果只使用 char
,则这些字符是有符号的。
It is safe. The error has to do with mixing unsigned integers of 8 bits with characters, that are signed if you use just char
.
但是,我看到该函数接受 uint8_t
并执行 char
acter算术运算,因此它应该接受 char
s(或 const char
s)。请注意,字符常量'c'
的类型为 char
,并且您在表达式中混合了有符号和无符号在 ihex_decode
内,因此您必须小心避免溢出或负数被视为大正数。
I see, however, that the function accepts uint8_t
and does char
acter arithmetic, so it should accepts char
s (or const char
s, for the matter). Note that a character constant 'c'
is of type char
, and you're mixing signed and unsigned in the expressions inside ihex_decode
, so you have to be careful to avoid overflows or negative numbers treated as big positive numbers.
A最后的样式说明。由于未修改,因此应在中读取 const uint8_t *(或
const char *在
(如上)中。另一个样式错误(可能会导致非常严重的错误)是您接受 len
作为 size_t
,但是声明 i
循环变量为 uint8_t
。如果该字符串的长度超过255个字节怎么办?
A last style note. As in
is not modified, it should read const uint8_t* in
(or const char* in
, as of above) in the parameters. Another style error (that may lead to very bad errors) is that you accept len
as size_t
, but declare the i
loop variable as uint8_t
. What if the string is more than 255 bytes in length?
这篇关于将未签名的char *(uint8_t *)转换为const char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!