Skip to content

Negative numbers not represented by in-memory two's complement binary value when formatted with {b} #23267

@ZeikJT

Description

@ZeikJT

Zig Version

0.14.0-dev.3217+5b9b5e45c

Steps to Reproduce and Observed Behavior

Simply try and print a negative number with {b}

const num1: i16 = 210;
const num2: i16 = -210;
std.debug.print("{b}\n", .{ num1 }); // 11010010
std.debug.print("{b}\n", .{ num2 }); // -11010010

As you can see, the negative number is printing the positive bit pattern with a - prefix. This is not how the number is actually being represented in memory.

Check out how confusing this is:

std.debug.print("{b}\n", .{-210}); // -11010010
std.debug.print("{b}\n", .{0b1000000000000000 & -210}); // 1000000000000000

Expected Behavior

I would expect the number to be printed as it is in memory, with the two's complement bit pattern. The docs state that Zig uses two's complement and we can verify this in code by forcing the literal bits into an unsigned int before printing:

const num: i16 = -210;
const numU: u16 = @bitCast(num);
std.debug.print("{b}\n", .{ numU }); // 1111111100101110

The above is how I'd expect it to print -210 with {b} by default, without having to forcibly bitCast it to an unsigned.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugObserved behavior contradicts documented or intended behavior

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions