logoalt Hacker News

boricjtoday at 4:45 PM1 replyview on HN

If I understand it correctly, it basically boils down to copying bits from the source to the destination, in order from the least significant bit to the most significant bit. It's not equivalent to C++'s reinterpret_cast.

I'm no Zig expert, but if you want endian-dependent semantics I'd assume either @ptrCast or a packed union would do the job.


Replies

tremontoday at 4:58 PM

But doesn't that show why this is a bad idea? If I understand correctly, this code:

  const MyUnion = packed union {
    full: u16,
    bytes: [2]u8,
  };
  const value: u16 = 0x55aa;
  const in_union: MyUnion = @bitCast(value);
  const without_union: [2]u8 = @bitCast(value);
  std.debug.assert(without_union[0] == in_union.bytes[0]);
  std.debug.assert(without_union[1] == in_union.bytes[1]);
...will now succeed or fail depending on the endianness of the target. That looks like the type of footgun that will bring decades of joy.
show 2 replies