Skip to content

behavior and documentation of right shift on signed integers differs #21709

@scottredig

Description

@scottredig

Zig Version

0.14.0-dev.1913+7b8fc18c6

Steps to Reproduce and Observed Behavior

When doing a right shift on a negative signed integer, 1 is shifted in for the missing significant digits, this is the behavior my code needs:

const std = @import("std");

pub fn main() void {
    const value: i8 = -5;
    const value_bits: u8 = @bitCast(value);

    const shifted = value >> 1;
    const shifted_bits: u8 = @bitCast(shifted);
    std.debug.print("Value:   {b} {d}\n", .{ value_bits, value });
    std.debug.print("Shifted: {b} {d}\n", .{ shifted_bits, shifted });
}

Produces this result:

Value:   11111011 -5
Shifted: 11111101 -3

However, language reference states

Bit Shift Right

Moves all bits to the right, inserting zeroes at the most-significant bit.

Expected Behavior

The language reference state the correct behavior, assuming that it is the intended behavior.

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