From f5c850f0982eee4881def95578d0b2b052d2c2ad Mon Sep 17 00:00:00 2001 From: Arceliar Date: Sat, 9 Jun 2018 16:36:13 -0500 Subject: [PATCH] better way to do wire signed ints (no negative zero, remove conditionals) --- src/yggdrasil/wire.go | 19 +++++-------------- 1 file changed, 5 insertions(+), 14 deletions(-) diff --git a/src/yggdrasil/wire.go b/src/yggdrasil/wire.go index 3b43143..23e9ab3 100644 --- a/src/yggdrasil/wire.go +++ b/src/yggdrasil/wire.go @@ -66,23 +66,14 @@ func wire_decode_uint64(bs []byte) (uint64, int) { } func wire_intToUint(i int64) uint64 { - var u uint64 - if i < 0 { - u = uint64(-i) << 1 - u |= 0x01 // sign bit - } else { - u = uint64(i) << 1 - } - return u + // Non-negative integers mapped to even integers: 0 -> 0, 1 -> 2, etc. + // Negative integres mapped to odd integes: -1 -> 1, -2 -> 3, etc. + // This means the least significant bit is a sign bit. + return ((uint64(-(i+1))<<1)|0x01)*(uint64(i)>>63) + (uint64(i)<<1)*(^uint64(i)>>63) } func wire_intFromUint(u uint64) int64 { - var i int64 - i = int64(u >> 1) - if u&0x01 != 0 { - i *= -1 - } - return i + return int64(u&0x01)*(-int64(u>>1)-1) + int64(^u&0x01)*int64(u>>1) } ////////////////////////////////////////////////////////////////////////////////