abs.go (757B)
1 package bitutil 2 3 // Abs8 returns the absolute value of i (calculated without branching). 4 func Abs8(i int8) int8 { 5 const bits = 8 6 u := uint64(i >> (bits - 1)) 7 return (i ^ int8(u)) + int8(u&1) 8 } 9 10 // Abs16 returns the absolute value of i (calculated without branching). 11 func Abs16(i int16) int16 { 12 const bits = 16 13 u := uint64(i >> (bits - 1)) 14 return (i ^ int16(u)) + int16(u&1) 15 } 16 17 // Abs32 returns the absolute value of i (calculated without branching). 18 func Abs32(i int32) int32 { 19 const bits = 32 20 u := uint64(i >> (bits - 1)) 21 return (i ^ int32(u)) + int32(u&1) 22 } 23 24 // Abs64 returns the absolute value of i (calculated without branching). 25 func Abs64(i int64) int64 { 26 const bits = 64 27 u := uint64(i >> (bits - 1)) 28 return (i ^ int64(u)) + int64(u&1) 29 }