Reinterpreting bytes

Hey gang, looking for the idiomatic way to reinterpret some bytes.

An example, I have some array of input bytes, I want to grab 4 bytes in the middle and then work with the value those bytes represent as a u32. Right now, I’m doing something like this:

    // input: [20]u8, offset: usize
    var bytes: [4]u8 = undefined;
    for (0..4) |i| {
        bytes[3-i] = input[offset + i];
    }
    const bytes_as_u32: u32 = @bitCast(bytes);

I’d like to take a slice (input[offset..offset+4]) but I haven’t found a clean way to cast that back to the array and/or just cast it.

Anyone have another approach they like?

std.mem.bytesAsValue though for ints also check std.mem.readInt (also in reader interface)
input[offset..][0..4] gives you a comptime known bound which you could @bitCast and so on …

1 Like

You’re looking for std.mem.bytesToValue or std.mem.bytesAsValue!
bytesToValue will give you copy the bytes, giving you a new value, while bytesAsValue will give you a pointer to the bytes as a pointer to your desired type.

Your example code can be rewritten as:

const bytes_as_u32 = std.mem.bytesToValue(u32, bytes[offset .. offset + 4];

Some other functions also worth mentioning are std.mem.bytesAsSlice which lets you turn a slice of bytes into a slice of Ts, as well as toBytes, asBytes, and sliceAsBytes, which turn other types into slices of bytes.

4 Likes