#How to divide u32 into 4 u8's as an array?

1 messages · Page 1 of 1 (latest)

eager wedge
#

?

#

Actually i want to read a string that is 4 characters length it is guaranteed but when i try to print the u32 as a string since it cannot be possible i want to divide u32 as 4 bytes so that i can print each byte as a character

mellow nexus
#

std.mem.sliceAsBytes? it will have different results on little-endian and big-endian machines though

#

how did you get a string in a u32 in the first place?

eager wedge
#

iam reading it from a file

#

like i have pakced struct and iam reading struct

mellow nexus
#

you could put it in the packed struct as [4]u8 instead of u32

eager wedge
#

so for the tag it is u32 but it is a string

eager wedge
#

let me try

mellow nexus
#

just don't try to do that with non-power of two ints. [4]u1 won't work, it will take up four bytes

eager wedge
#

no i have put [4]u8 it is not taking

#

packed structs dont have a field [4]u8

mellow nexus
#

what do you mean? show me the packed struct

eager wedge
#

ok

#
const TableDirectory = packed struct {
    tag: [4]u8,
    checksum: u32,
    offset: u32,
    length: u32,
};```
mellow nexus
#

oh ok nevermind then

#

std.mem.sliceAsBytes(&[_]u32{packed_struct.tag}) should work

eager wedge
#

ok

raw widget
#

or std.mem.asBytes for a single item