hl037_
hl037_

Reputation: 3907

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. But on the micro controller I'm using, an address points to 2 bytes.

Is there a way to know the number of byte an address points to ? (like in macro or something else)

Upvotes: 1

Views: 354

Answers (2)

Billy ONeal
Billy ONeal

Reputation: 106609

"byte" means "the smallest addressable unit" on a machine; one address always identifies one byte. On some machines, a byte will be 8 bits; on others, it could be 32 bits.1

The C standard defines char to be the smallest addressable unit on a machine2; and the macro CHAR_BIT for the number of bits in that unit. It will be a macro in <limits.h> / <climits>.


1 C99 6.2.6.1 footnote 40 says:

A byte contains CHAR_BIT bits, and the values of type unsigned char range from 0 to 2CHAR_BIT−1.

2 Not strictly true but strongly implied by e.g. C99 6.2.6.1/4:

Values stored in non-bit-field objects of any other object type consist of n × CHAR_BIT bits, where n is the size of an object of that type, in bytes.

which says that sizeof(char) == 1

Upvotes: 7

unwind
unwind

Reputation: 400109

The macro CHAR_BIT evaluates to an integer which is the number of bits in a char on the target platform.

The point of char is to capture the smallest single addressable unit of memory on the target platform. This is often called a "byte", and does not have to be 8 bits.

The proper term for an 8-bit quantity is an octet. In practice, 8-bit bytes are so common that the term has shifted in meaning.

You get access to the CHAR_BIT macro by doing

#include <limits.h>

Upvotes: 3

Related Questions