#Cast u1 slice to u16

1 messages · Page 1 of 1 (latest)

blissful wasp
#
var ram align(2): [128]u1 = undefined;
// ... modifying ram
std.debug.print("{}\n", .{ @as([]u16, @ptrCast(ram[0..16]))});

Should the compiler not allow this or am I misunderstanding something?
Casting from []u1 to:

  • []u16 compile error: error: TODO: implement @ptrCast between slices changing the length
  • [*]u16 works, but the value of [0] seems to always be 0
  • *u16 same as above with the multi ptr
    Casting from ([0..16]ram).* seems to show why it isn't working: error: @bitCast size mismatch: destination type 'u16' has 16 bits but source type '[16]u1' has 121 bits
    So, in the end is there a quick way to convert from []u1 to u16 and is there such a thing as a packed array?
#

Cast u1 slice to u16

leaden crane
#
  • The individual u1 elements are padded to u8 since they're not inside a packed struct/union. Without padding, what would be the addresses of &u1_array[1] and &u1_array[2]? You're intuition at the end is right; there's https://ziglang.org/documentation/master/std/#A;std:PackedIntArray
  • undefined isn't zero. It means "could be any value" and is similar to leaving it uninitialized in C. This means trying to observe or branch on it is UB so anything could happen (at runtime).
fluid barn
#

perhaps this is similar to the kind of thing you're looking to do:

const std = @import("std");
test {
    const Arr = std.PackedIntArray(u1, 128);
    var arr = Arr.initAllTo(0);
    const x = arr.sliceCast(u16).get(0);
    std.debug.print("x={}\n", .{x});
}
blissful wasp