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“无符号字符*"


基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01