Implicit conversion to uint8_t

S

Spoon

Hello,

The typedef name uint8_t designates an unsigned integer type
with width exactly 8. (I am only interested in platforms where
uint8_t is defined.)

Are the two following code fragments equivalent on every
platform where uint8_t is defined?

int u = something;
uint8_t buf[100];
buf[66] = u;

vs

int u = something;
uint8_t buf[100];
buf[66] = u & 0xff;

Similarly, are the two following statements equivalent?

buf[66] = u >> 8;
vs
buf[66] = (u >> 8) & 0xff;

Is there any difference if u is of type long int?
What if u is of an unsigned type?

Regards.
 
E

Eric Sosman

Spoon said:
Hello,

The typedef name uint8_t designates an unsigned integer type
with width exactly 8. (I am only interested in platforms where
uint8_t is defined.)

Are the two following code fragments equivalent on every
platform where uint8_t is defined?

int u = something;
uint8_t buf[100];
buf[66] = u;

vs

int u = something;
uint8_t buf[100];
buf[66] = u & 0xff;

Yes if `something' is non-negative or if negative `int'
values use two's complement representation. No if `something'
is negative and `int' uses signed magnitude or ones' complement.
Similarly, are the two following statements equivalent?

buf[66] = u >> 8;
vs
buf[66] = (u >> 8) & 0xff;

As above, with the added fillip that right-shifting a
negative `int' gives an implementation-defined result that
is not required to make sense.
Is there any difference if u is of type long int?

Only if `something' is out of range for a plain `int'.
What if u is of an unsigned type?

If `u' is unsigned, the pairs of code fragments are
equivalent and all the complications disappear. (That's
why people prefer to use unsigned types for bit-bashing.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top