Integer to byte

I have been using a library for a SPI device and the data type of the library function is a byte variable.

I wanted to assign a value to it but the variable of the value is in integer, so in respect of the byte’s number range (00-FF or 0-255), I made sure the integers are not to exceed the range.

With that taken into account, will there be any problem if I assign the integer value to the byte?

You can cast a integer with value 0…255 to a byte without problem.

byte b;
int i;

// remove the high byte
b = (byte) (i & 0x00FF);

// drop the high byte just like that, but 'i' might be negative.
b = (byte) i;

// clip
if( i < 0)
  i = 0;
else if( i > 255)
  i = 255;
b = (byte) i;

// constrain
i = constrain( i, 0, 255);
b = (byte) i;
1 Like

You don’t even have to worry about the values. The compiler will happily throw away all but the bottom 8 bits whan you store an integer value (short, int, long int, unsigned long int…) into a byte (unsigned char, uint8_t).

Thanks for the helpful explanation!