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?

1 Like

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.

2 Likes

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.

6 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

Isn’t it just because when printing an array, it prints from index 0 upwards, so when bitcasting, the least significant bit is in index 0, and gets printed first?

4 Likes

it is just due to how we write numbers (least significant digits on the right)