按字节读取的存储器:"符号字符*" VS"无符号字符*" [英] Bytewise reading of memory: "signed char *" vs "unsigned char *"
问题描述
一个经常需要从内存在同一时间在这个天真的的memcpy读一个字节,像()
实施
One often needs to read from memory one byte at a time, like in this naive memcpy()
implementation:
void *memcpy(void *dest, const void *src, size_t n)
{
char *from = (char *)src;
char *to = (char *)dest;
while(n--) *to++ = *from++;
return dest;
}
不过,我有时看到有人明确地使用无符号字符*
,而不是仅仅的char *
。
当然,字符
和 unsigned char型
可能不相等。但这是否有所作为我是否使用了的char *
,符号字符*
或符号字符*
时按字节读取/写入内存?
Of course, char
and unsigned char
may not be equal. But does it make a difference whether I use char *
, signed char *
, or unsigned char *
when bytewise reading/writing memory?
更新:其实,我充分认识到 C = 200
可能根据类型不同的值 C
。什么我问这是为什么人们有时会使用无符号字符*
,而不是仅仅的char *
读存储器时,例如为了存储一个 uint32_t的
在的char [4]
。
UPDATE: Actually, I'm fully aware that c=200
may have different values depending on the type of c
. What I am asking here is why people sometimes use unsigned char *
instead of just char *
when reading memory, e.g. in order to store an uint32_t
in a char[4]
.
推荐答案
您应该使用 unsigned char型
。 C99的标准说 unsigned char型
是保证是密集的(没有填充位),也是唯一的类型定义,你可以复制任何对象(除位域)正是通过复制它变成一个 unsigned char型
阵列,这是的对象重新presentation 的以字节为单位。
You should use unsigned char
. The C99 standard says that unsigned char
is the only type guaranteed to be dense (no padding bits), and also defines that you may copy any object (except bitfields) exactly by copying it into an unsigned char
array, which is the object representation in bytes.
这样做的合理intere pretation对我来说,如果你使用指针访问对象为字节,你应该使用 unsigned char型
。
The sensible interepretation of this is to me, that if you use a pointer to access an object as bytes, you should use unsigned char
.
参考:<一href=\"http://blackshell.com/~msmud/cstd.html#6.2.6.1\">http://blackshell.com/~msmud/cstd.html#6.2.6.1 (摘自 C1X草案 C99)
Reference: http://blackshell.com/~msmud/cstd.html#6.2.6.1 (From C1x draft C99)
这篇关于按字节读取的存储器:&QUOT;符号字符*&QUOT; VS&QUOT;无符号字符*&QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!