Expected u3, but every varable is a u8

I am confused.

Here is a minimal reproducable sample:

pub fn main() void {
  const firstByte: u8 = 0b10000000;
  var col: u8 = 0;
  const bytes: u8 = 1;
  var colByte: u8 = bytes & (firstByte >> col);
  _ = colByte;

When compiling this, I get the following error:

An error occurred:
playground/playground1330700213/play.zig:5:43: error: expected type 'u3', found 'u8'
  var colByte: u8 = bytes & (firstByte >> col);
playground/playground1330700213/play.zig:5:43: note: unsigned 3-bit int cannot represent all possible unsigned 8-bit values
referenced by:
    callMain: /usr/local/bin/lib/std/start.zig:604:17
    initEventLoopAndCallMain: /usr/local/bin/lib/std/start.zig:548:51
    remaining reference traces hidden; use '-freference-trace' to see all reference traces

I don’t get why it says it’s expecting a u3 since all variable used are u8s.

The note makes it even more confusing.

>Solution :

From the documentation:

a >> b

Bit Shift Right.

  • b must be comptime-known or have a type with log2 number of bits as a.

In other words, the compiler expects you to use u3 because it can only represent 8 possible values, the exact number of bits the u8 type has.

Simply change col from u8 to u3 or use an @intCast:

var colByte: u8 = bytes & (firstByte >> @intCast(col));

Leave a Reply