#cast slice of [_]u8 to *u32

1 messages · Page 1 of 1 (latest)

solid pewter
#

Hi

I'm trying to update a value in a header I've currently got implemented a simple [8]u8 hdr. The value at hdr[4..8] is a little endian u32 I'm trying to update. So far I've got

 15    var hdr: [8]u8 = [8]u8{ 0x00, ..., 0x00, 0x00, 0x00, 0x00};
 16
 15    ...
23          const hdr_len_field: *u32 = ???;
  1         hdr_len_field.* = i + 1;
  2         _ = try conn.write(&hdr);
  3    ...

I've tried:

  • @alignCast(&hdr[4], which doesn't work as the underlying u8 can't be cast to a u32 (fair enough)
  • @ptrCast(&hdr[4], which doesn't work as the pointer alignment changes (are [*]u8 not contiguous?)
  • @ptrCast(hdr[4..8]), which doesn't work as it was a hailmary and you rawdog cast a slice to a u32, again, fair.

What should go in ????

restive root
#

you can do

#

@alignCast(@ptrCast())

#

alternatively, look at std.mem.writeInt(), its likely what you are looking for

#
var hdr: [8]u8 = .{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
std.mem.writeInt(u32, hdr[4..8], 0xabcd, .little);
std.debug.print("{x}", .{hdr});
// { 0, 0, 0, 0, cd, ab, 0, 0 }