# Implicit conversion to uint8_t

Discussion in 'C Programming' started by Spoon, Feb 14, 2008.

1. ### SpoonGuest

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.

Spoon, Feb 14, 2008

2. ### Eric SosmanGuest

Spoon wrote:
> 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.)

--
Eric Sosman
lid

Eric Sosman, Feb 14, 2008