How can I typecast an array (of bytes) to a struct?

How can I do the above conversion?

Hey, welcome to Ziggit!

Have a look at std.mem.bytesAsValue() and std.mem.bytesToValue(). All they do is use @ptrCast() to convert from a pointer to an array of bytes / a byte slice to a pointer to another type T (e.g. your struct).
When casting memory like this always keep in mind that many containers in Zig don’t have a guaranteed in-memory layout (for example plain structs) so casting them from/to raw bytes is only valid inside the same compilation unit.

1 Like

Thanks! Is there a class declaration in zig? I tried the chatgpt samples (this one uses, bytesasvalue) but it was wrong…

1 Like

No there are no classes in Zig. Have a look at Learn ⚡ Zig Programming Language (particularly Ziglings), ChatGPT isn’t very good at writing Zig code.

1 Like

Thanks again Justus!

1 Like

No problem :slight_smile:

Very true, although it seems a tiny bit better than in 2024.

1 Like

One of the very last opportunities to learn to actually program, that. Enjoy it while it lasts.

I’ve made my peace with spending the rest of my career dealing with learned helplessness in junior engineers, for whom programming is the act of asking a chatbot to do things. I hope some of you kids pleasantly surprise me.

3 Likes

I know some people who bought the “premium membership chat gpt” and are playing zen master copy-pasting generated code.
That said and off topic: Almost everything has a premium membership variant. It is the age of premium memberships. The disgust I feel is beyond description.

Regarding the question: indeed we have to be very careful with raw bytes versus structs.

2 Likes

Surprise :slight_smile: from me and my fellow youngens that are here because we enjoy programming and are under no illusion that programming is a skill that extends beyond patterns in written language.

2 Likes