I don't understand writeIntLittle / writeIntBig

source:

const std = @import("std");

pub fn main() !void {
    const stdout = std.io.getStdOut().writer();

    const a: u16 = 0b01111110_00000000;
    const b: u16 = 0b00000000_01111110;
    try stdout.print("0b01111110_00000000 = {d}\n", .{a});
    try stdout.print("0b00000000_01111110 = {d}\n", .{b});

    try stdout.writeIntForeign(u16, a);
    try stdout.writeByte('\n');
    try stdout.writeIntNative(u16, b);
    try stdout.writeByte('\n');

    try stdout.writeIntLittle(u16, a);
    try stdout.writeByte('\n');
    try stdout.writeIntLittle(u16, b);
    try stdout.writeByte('\n');

    try stdout.writeIntBig(u16, a);
    try stdout.writeByte('\n');
    try stdout.writeIntBig(u16, b);
    try stdout.writeByte('\n');
}

output:

0b01111110_00000000 = 32256
0b00000000_01111110 = 126
~
~
~
~
~
~

why does both a and b always print as ~(ascii 126)?

Haven’t looked into it deeply, but I am guessing that the zero byte becomes the null control character and that that is filtered out by your terminal emulator.

Maybe you should write to a file instead if you want to see what you are writing exactly.
And then use tools that treat the file as binary, like a hex viewer to confirm that it works as intended.

ok I think it’s a ternimal display issue

it works when I write it to the file:

const std = @import("std");
const fs = std.fs;

pub fn main() !void {
    const stdout = std.io.getStdOut().writer();

    const cwd = fs.cwd();
    var f = try cwd.createFile("output.txt", .{ .read = true });
    defer f.close();

    const a: u16 = 0b01111110_00000000;
    const b: u16 = 0b00000000_01111110;
    try stdout.print("0b01111110_00000000 = {d}\n", .{a});
    try stdout.print("0b00000000_01111110 = {d}\n", .{b});

    var writer = f.writer();

    try writer.writeIntForeign(u16, a);
    try writer.writeByte('\n');
    try writer.writeIntNative(u16, a);
    try writer.writeByte('\n');

    try writer.writeIntLittle(u16, a);
    try writer.writeByte('\n');
    try writer.writeIntLittle(u16, b);
    try writer.writeByte('\n');

    try writer.writeIntBig(u16, a);
    try writer.writeByte('\n');
    try writer.writeIntBig(u16, b);
    try writer.writeByte('\n');

    const reader = f.reader();
    var buf: [10000]u8 = .{};

    try f.seekTo(0);
    while (try reader.readUntilDelimiterOrEof(&buf, '\n')) |line| {
        try stdout.print("{b}\n", .{line});
    }
}
0b01111110_00000000 = 32256
0b00000000_01111110 = 126
{ 1111110, 0 }
{ 0, 1111110 }
{ 0, 1111110 }
{ 1111110, 0 }
{ 1111110, 0 }
{ 0, 1111110 }

That’s simply one of the bytes in your a and b numbers there:

$ python
>>> 0b01111110
126
>>> chr(0b01111110)
'~'

writer.writeInt*() writes it to a buffer raw, it doesn’t translate the number to a string. So I guess suboptimal naming choice. :slight_smile: