剛剛在自己實作正負數轉換為絕對值的function
func main() {
v := abs(-126)
log.Println(v)
}
func abs(x int) int {
con := x >> 63
return (x ^ con) - con
}
我有自己寫成二進制用手算過,這個流程我懂
但問題有兩個
請各路大神賜教...
package main
import (
"fmt"
"strconv"
)
func main() {
v := abs(-126)
fmt.Print(v)
}
func abs(x int) int {
x64 := int64(x)
con := x >> 63
con64 := int64(con)
fmt.Println("x = ", strconv.FormatInt(x64, 2), "(", x, ")")
fmt.Println("con = ", strconv.FormatInt(con64, 2), "(", con, ")")
fmt.Printf("x ^ con = %s ^ %s = %d\n", strconv.FormatInt(con64, 2), strconv.FormatInt(x64, 2), (x ^ con))
fmt.Printf("(x ^ con) - con = %d - %d = %d\n", (x ^ con), con, (x ^ con) - con)
return (x ^ con) - con
}