Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting int to uint8_t

is it a correct way to convert an int value to uint8_t:

int x = 3; 
uint8_t y = (uint8_t) x;

assume that x will never be less than 0. Although gcc does not give any warning for the above lines, I just wanted to be sure if it is correct to do it or is there a better way to convert int to uint8_t?

P.S. I use C on Linux if you are going to suggest a standard function

like image 226
Johan Elmander Avatar asked Jul 26 '13 13:07

Johan Elmander


1 Answers

It is correct but the cast is not necessary:

uint8_t y = (uint8_t) x;

is equivalent to

uint8_t y = x;

x is implicitely converted to uint8_t before initialization in the declaration above.

like image 85
ouah Avatar answered Sep 19 '22 07:09

ouah