#left shifting

1 messages · Page 1 of 1 (latest)

plucky salmon
#

I'm really confused here, and to be fair maybe it is from being used to left shifting by arbitrary values in C and C++.

I'm trying to shift a u8 var by a u32 var... and it gives an error saying the shift needs to be a u3. I read the documentation and it says that the shift must be a log2 of the width of the value to shift.

so.... what how should I proceed ?

pearl sigil
#

@intCast(u3, the_u32_var)

plucky salmon
#

thanks!

#

but I also have a bit of follow-up question... why is it this way in zig? what is the philosophy behind having it done this way ?

#

because i suppose things like u3 are not natively supported by x86 for example.. ?

pearl sigil
#

Well, shifting by any more than a u3 does nothing, because it's a u8. So it's more explicit about the type.

plucky salmon
#

i see...

pearl sigil
#

the u3 is practically going to be a u8 once it compiles (because there is no u3 in hardware)

#

Let's say you had 9 in the u32. If you shift by 9, it doesn't really make sense, because you're shifting a u8. So the @intCast will actually fail, which is good to know.

plucky salmon
#

ah i see, all this comes down to no explicit type coersions right ?

pearl sigil
#

pretty much I guess

plucky salmon
#

like C will just make the uint8_t into a larger integer if I try to shift by a value greater than 7

pearl sigil
#

I can't remember how C would do it, but if it does that, it is a sort of footgun.