I'm pretty sure this can be written as a couple of lines, but I'm unable to come up with a better solution.
package main
import (
"fmt"
"math/big"
)
func colonedSerial(i *big.Int) string {
hex := fmt.Sprintf("%x", i)
if len(hex)%2 == 1 {
hex = "0" + hex
}
numberOfColons := len(hex)/2 - 1
colonedHex := make([]byte, len(hex)+numberOfColons)
for i, j := 0, 0; i < len(hex)-1; i, j = i+1, j+1 {
colonedHex[j] = hex[i]
if i%2 == 1 {
j++
colonedHex[j] = []byte(":")[0]
}
}
// we skipped the last one to avoid the colon at the end
colonedHex[len(colonedHex)-1] = hex[len(hex)-1]
return string(colonedHex)
}
func main() {
fmt.Println(colonedSerial(big.NewInt(1234)))
// "04:d2"
fmt.Println(colonedSerial(big.NewInt(123456)))
// "01:e2:40"
fmt.Println(colonedSerial(big.NewInt(1234567891011121314)))
// "11:22:10:f4:b2:d2:30:a2"
}
Also the []byte(":")[0]
is very ugly. Is there a better way to do that? (I did not wanted to write the ASCII value of colon (58) as it would be a magic number).
Go Playground version: https://play.golang.org/p/GTxajcr3NY