按字节读取内存:“signed char *"vs“无符号字符*"

2022-01-12 00:00:00 c char coding-style c++ unsigned-char

通常需要一次从内存中读取一个字节,就像在这个简单的 memcpy() 实现中一样:

void *memcpy(void *dest, const void *src, size_t n){char *来自 = (char *)src;char *to = (char *)dest;while(n--) *to++ = *from++;返回目的地;}

但是,我有时会看到人们明确使用 unsigned char * 而不仅仅是 char *.

当然,charunsigned char 可能不相等.但是在按字节读取/写入内存时,我使用 char *signed char * 还是 unsigned char * 有区别吗?p>

更新: 实际上,我完全知道 c=200 可能具有不同的值,具体取决于 c 的类型.我在这里要问的是为什么人们有时在读取内存时使用 unsigned char * 而不仅仅是 char * ,例如为了将 uint32_t 存储在 char[4] 中.

解决方案

你应该使用 unsigned char.C99 标准说 unsigned char 是唯一保证密集(无填充位)的类型,并且还定义您可以通过将任何对象(位域除外)复制到 unsigned char 数组,即对象表示,以字节为单位.

对我来说,明智的解释是,如果您使用指针以字节形式访问对象,则应该使用 unsigned char.

参考:http://blackshell.com/~msmud/cstd.html#6.2.6.1(来自C1x草案 C99)

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;
}

However, I sometimes see people explicitly use unsigned char * instead of just 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?

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].

解决方案

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.

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.

Reference: http://blackshell.com/~msmud/cstd.html#6.2.6.1 (From C1x draft C99)

相关文章