Why @bitCast reverses bits when casting type to array?

For this code

const num1: u8 = 0b01010101;
std.debug.print("{any}\n", .{@as([8]u1, @bitCast(num1))});

You would expect the result to be:

{ 0, 1, 0, 1, 0, 1, 0, 1 }

But instead it prints:

{ 1, 0, 1, 0, 1, 0, 1, 0 }

So with fliped bits. Why is that the case?

I am confused by that code and baffled by the @as([8]u1, ...) which would assume a bitpacked array? Did not run it yet though…

The output seems logical. the LSB is printed first.

1 Like

Devlog :high_voltage: New @bitCast Semantics and LLVM Backend Improvements

Every type which supports @bitCast has a “logical bit layout”—a representation of that type as an ordered sequence of bits. For instance, u5 is composed of 5 logical bits, which we order from least-significant to most-significant.

EDIT:
Just to add more context, this is a new change (i.e part of 0.17.0), and the whole article is worth looking into and reading.

4 Likes

Aha! still using 0.15.2 because of the deleted vectorizing loops in >= 0.16.
So I did not know :slight_smile:

Oh wow, that is really interesting. I will definitely look into that. Thank you