I'm trying to learn go and hating myself
package main
import (
"fmt"
"strconv"
)
func main() {
fmt.Println(sum(3,255))
}
func sum(one, two uint8) (out uint16) {
var outBits [8]byte
sum, carry := halfAdder( getBit(one, 0), getBit(two, 0) )
if sum {
outBits[0] = '1'
} else {
outBits[0] = '0'
}
for i := 7; i >= 0; i-- {
sum, carry = fullAdder( getBit(one, i), getBit(two, i), carry )
if sum {
outBits[i] = '1'
} else {
outBits[i] = '0'
}
}
var carryChar string
if carry {
carryChar = "1"
} else {
carryChar = "0"
}
out64,_ := strconv.ParseUint(carryChar + string(outBits[:8]), 2, 16)
out = uint16(out64)
return
}
func halfAdder(one bool, two bool) (sum bool, carry bool) {
sum = one != two
carry = one && two
return
}
func fullAdder(one bool, two bool, carryIn bool) (sum bool, carryOut bool) {
xor := one != two
sum = xor != carryIn
and1 := one && two
and2 := xor && carryIn
carryOut = and1 || and2
return
}
func getBit(value uint8, pos int) bool {
bin := strconv.FormatUint(uint64(value), 2)
binLen := len(bin)
var bin8 [8]byte
for i := 0; i < (8-binLen); i++ {
bin8[i] = '0'
}
for i := (8-binLen); i < 8; i++ {
bin8[i] = bin[i-(8-binLen)]
}
return bin8[pos] == 49
}