converting int to uint8_t
Asked Answered
G

1

17

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

Gant answered 26/7, 2013 at 13:21 Comment(5)
What would qualify as a better way ?Seumas
There is no need for the cast. Simply y = x; is fine.Grata
Nbr44, I mean with a better way is that if there is a standard way or if the above conversion could cause a problem and the alternative suggestion would not cause that problem.Gant
Even if it is obvious, be careful about overflowing your uint8_t.Pierro
@R..: Recommending y = x; instead of uint8_t y = x; can introduce a bug if there is a previously declared y in scope.Lycaonia
C
23

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.

Croatia answered 26/7, 2013 at 13:28 Comment(5)
Unless you're working with Visual Studio, in which case you'll need a & 0xff to keep it from complaining :PConsubstantiation
Assuming that int can fit in short.Scend
@DrewMcGowen no diagnostic is required by C, this is a valid declaration and the implementation cannot refuse to do the translation but of course the implementation is free to issue an extra informational message.Croatia
@Croatia yes I'm aware of it, just thought I should point out VS's behaviorConsubstantiation
@EricPostpischil fixed. I always have in mind this C quote for initialization the same type constraints and conversions as for simple assignment apply.Croatia

© 2022 - 2024 — McMap. All rights reserved.