#Why does this produce an InvalidCharacter error?

1 messages · Page 1 of 1 (latest)

nova ivy
#
const std = @import("std");

pub fn main() !void {
    var bytes: [3]u8 = .{ 0, 0, '4' };
    bytes[1] = '4';
    bytes[2] = '2';

    const val = try std.fmt.parseInt(u8, &bytes, 10);
    std.debug.print("Parsed bytes {s} as {d}\n", .{ bytes, val });
}

In this example, I am trying to construct a string of integer characters and then parse that string into a u8. However, this produces the following output:

$ zig build run                                                                                                                                                                                                                                                                                                
error: InvalidCharacter                                                                                                                                                                                                                                                                                                       
/usr/lib64/zig/9999/lib/std/fmt.zig:1763:17: 0x1072362 in charToDigit (tmp_zig)                                                                                                                                                                                                                                               
        else => return error.InvalidCharacter,                                                                                                                                                                                                                                                                                
                ^                                                                                               
<snip, message too long>

what's the correct way to build this string piece-by-piece and then later convert to an integer?

versed junco
#

0 isn't a valid digit.

#

'0' would be.

nova ivy
#

🤦

#

ofc

#

that was totally it!

#

is there a std helper that will allow me to prefill the array with 0?

versed junco
#

there is, but ** does it too

nova ivy
#

ah, I'll take a look at ** thanks

versed junco
#
var bytes: [3]u8 = .{'0'} ** 3;
#

I was thinking of std.mem.zeroInit but it doesn't work to initialize members of an array. std.mem.zeroes then doesn't let you supply a default. So it's really only ** here

nova ivy
#

yup, I was already ausing std.mem.zeroes, but you're right that ** is the right approach

ripe oasis
#

@memset(&bytes, '0');