Converting []u8 to u64


I am new to the Zig language and I am trying to convert the entropy variable to a u64 value, the following code does not seem to work properly:

pub export fn GenerateEntropySeed64() u64 {
    // Allocate memory to store the entropy
    const entropyLength = 8;
    var entropy: [entropyLength]u8 = undefined;

    // Retrieve entropy from the platform-specific source
    _ = std.os.getrandom(&entropy) catch unreachable; // std.os.getrandom can trigger an exception

    var result: u64 = 0;
    var shift: u8 = 0;

    for (entropy) |byte| {
       const byteU64: u64 = @intCast(byte);
       result |= byteU64 << @intCast(shift);
       shift += 8;

   return result;

Thank you in advance!

I don’t know of the top of my head what the issue with the code here is. But in general, for the use case of converting slices of u8 to integers, I’d use std.mem.readInt. link to std library doc.


Thank you, it worked!

Another way is to cast u64 to [8]u8 using std.mem.asBytes

fn GenerateEntropySeed64() u64 {
    var seed: u64 = undefined;
    std.os.getrandom(std.mem.asBytes(&seed)) catch unreachable;
    return seed;