Bytewise reading of memory: quot;signed char *quot; vs quot;unsigned char *quot;(按字节读取内存:“signed char *vs“无符号字符*)
问题描述
通常需要一次从内存中读取一个字节,就像在这个简单的 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 *.
当然,char 和 unsigned 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)
这篇关于按字节读取内存:“signed char *"vs“无符号字符*"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:按字节读取内存:“signed char *"vs“无符号字符*"
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
