[英]C/C++ : how to get the number of bytes addressed by one address
On most x86 / x86_64 architectures, one address points to one byte. 在大多数x86 / x86_64体系结构中,一个地址指向一个字节。 But on the micro controller I'm using, an address points to 2 bytes.
但是在我使用的微控制器上,地址指向2个字节。
Is there a way to know the number of byte an address points to ? 有没有办法知道地址指向的字节数? (like in macro or something else)
(例如宏或其他内容)
"byte" means "the smallest addressable unit" on a machine; “字节”是指机器上的“最小可寻址单元”; one address always identifies one byte.
一个地址总是标识一个字节。 On some machines, a byte will be 8 bits;
在某些机器上,一个字节为8位。 on others, it could be 32 bits.
在其他情况下,可能是32位。 1
1个
The C standard defines char
to be the smallest addressable unit on a machine 2 ; C标准将
char
定义为机器2上最小的可寻址单元。 and the macro CHAR_BIT
for the number of bits in that unit. 宏
CHAR_BIT
表示该单元中的位数。 It will be a macro in <limits.h>
/ <climits>
. 这将是
<limits.h>
/ <climits>
的宏。
1 C99 6.2.6.1 footnote 40 says: 1 C99 6.2.6.1脚注40说:
A byte contains
CHAR_BIT
bits, and the values of typeunsigned char
range from0
to 2 CHAR_BIT −1.一个字节包含
CHAR_BIT
位,并且unsigned char
类型的值的范围为0
到2 CHAR_BIT -1。
2 Not strictly true but strongly implied by eg C99 6.2.6.1/4: 2并非严格正确,但例如C99 6.2.6.1/4强烈暗示:
Values stored in non-bit-field objects of any other object type consist of
n
×CHAR_BIT
bits, wheren
is the size of an object of that type, in bytes.存储在任何其他对象类型的非位字段对象中的值由
n
×CHAR_BIT
位组成,其中n
是该类型对象的大小(以字节为单位)。
which says that sizeof(char) == 1
它说
sizeof(char) == 1
The macro CHAR_BIT
evaluates to an integer which is the number of bits in a char
on the target platform. 宏
CHAR_BIT
计算结果是一个整数,该整数是目标平台上char
的位数。
The point of char
is to capture the smallest single addressable unit of memory on the target platform. char
的要点是捕获目标平台上最小的单个可寻址内存单元。 This is often called a "byte", and does not have to be 8 bits. 这通常称为“字节”,不必为8位。
The proper term for an 8-bit quantity is an octet . 8位数量的适当术语是八位位组 。 In practice, 8-bit bytes are so common that the term has shifted in meaning.
实际上,8位字节非常普遍,以至于该术语的含义已发生变化。
You get access to the CHAR_BIT
macro by doing 您可以通过以下方式访问
CHAR_BIT
宏
#include <limits.h>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.