The Crystal Programming Language Forum

Error: can't cast UInt32 to UInt8

The compiler doesn’t like this line:

(1 + roll % 10).as(UInt8)

What is the correct syntax? “roll” is a method returning a random UInt32. I tried replacing 1 with 1_u32, in case it was being taken as signed. The value being made into 8-bit is always in the range 1 … 10, so overflow isn’t a problem. I’m likely overlooking something obvious, due to being brainwashed in other languages that let one cast types as one pleases.

You can do .unsafe_as(UInt8) if you are cool hacker and understand consequences, or just .to_u8 (or UInt8.new(1+roll % 10)) to make a conversion, not a cast.

Use to_u8. Anything that has “unsafe” in its name shouldn’t be recommended unless there is a good reason.

Theres also to_u8 which won’t raise on overflow and just keep the lower bits.

1 Like

.to_u8 works.

I have no idea what is the difference between .as(UInt8) vs .to_u8, and haven’t see .unsafe_as( ) before - what good is that?

Maybe to_u8 needs a better explanation, but it tries to fit the value in the integer type into Int8, and raises overflow if that doesn’t fit.