#How do i convert numbers for writing to binary file?

1 messages · Page 1 of 1 (latest)

vivid crypt
#

Is the following approach correct or is there a better way?

pub fn encodeNumber(comptime T: type, value: T) [@sizeOf(T)]u8 {
    var bytes: [@sizeOf(T)]u8 = undefined;
    std.mem.writeInt(T, &bytes, value, std.builtin.Endian.little);
    return bytes;
}
pub fn encodeFloat(comptime T: type, value: T) [@sizeOf(T)]u8 {
    var bytes: [@sizeOf(T)]u8 = undefined;

    switch (@sizeOf(T)) {
        2 => bytes = encodeNumber(u16, @as(u16, @bitCast(value))),
        4 => bytes = encodeNumber(u32, @as(u32, @bitCast(value))),
        8 => bytes = encodeNumber(u64, @as(u64, @bitCast(value))),
        else => unreachable,
    }
    return bytes;
}
vague orchid
#

std.mem.asBytes?

vivid crypt
#

I am not able to figure out how to use std.mem.asBytes with different endians or how to supply values with specific types. for example how would i convert -1.5 as f16 bytes or f32 bytes using little endian?

vague orchid
#

if you want the same endian as the system: use asBytes directly
if you want the opposite endian as the system: @byteSwap the value and then use asBytes

vivid crypt
#

Thanks. How do i identify if system endian is little or big?

vivid crypt
#

Is this what you meant? @bitCast(if (endian == native_endian) value else @byteSwap(value))