Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Eh the author's suggestions only seem better because C++ is insane.

The last one is definitely nice though!



Can you post examples in other languages where this would be easier?


Zig:

    fn signExtend(raw: u11) i32 {
        return @as(i11, @bitCast(raw));
    }

    test "signExtend" {
        try expectEqual(1023, signExtend(1023));
        try expectEqual(-1, signExtend(2047));
    }


Sure, in Rust:

  fn sign_extend_u11(x: u32) -> u32 {
    (((x as i32) << (32-11)) >> (32-11)) as u32
  }
Doesn't have any of the C++ issues he mentions. And it will be faster than the alternative since it's just two instructions. (Ok this is never going to matter in practice but still...)


Shifts run on less ports than xor/sub, so should be avoided if possible when performance is important, especially when using SIMD where the shifts are often quite subpar.


Isn’t the alternative also two instructions:

  x ^ 0x400 - 0x400


But the C++20 code doesn't have this issue. That's my point. C++20 is 4 years old by this point.


The first piece of code is perfect in Java:

    int t = (val_11b << (32 - 11)) >> (32 - 11).




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: