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


基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01