Skip to content

Instantly share code, notes, and snippets.

@rof20004
Last active March 9, 2024 11:39
Show Gist options
  • Save rof20004/15eb11cd5f8c05d0766a887e2d815ae1 to your computer and use it in GitHub Desktop.
Save rof20004/15eb11cd5f8c05d0766a887e2d815ae1 to your computer and use it in GitHub Desktop.
Go example to convert binary to text and text to binary
package main
import (
"fmt"
"strconv"
"strings"
)
func textToBinary(s string) string {
var b string
for _, c := range s {
b = fmt.Sprintf("%s %.8b", b, c)
}
return strings.TrimSpace(b)
}
func binaryToText(s string) (x string) {
b := make([]byte, 0)
for _, s := range strings.Fields(s) {
n, _ := strconv.ParseUint(s, 2, 8)
b = append(b, byte(n))
}
x = string(b)
return
}
func numberToBinary(n int) string {
return fmt.Sprintf("%08b", n)
}
func binaryToNumber(s string) int {
num, err := strconv.ParseInt(s, 2, 0)
if err != nil {
return 0
}
return int(num)
}
func leftShiftBinary(binaryStr string, shiftAmount int) string {
paddedBinaryStr := binaryStr + strings.Repeat("0", shiftAmount)
resultBinary := paddedBinaryStr[shiftAmount:]
return resultBinary
}
func rightShiftBinary(binaryStr string, shiftAmount int) string {
paddedBinaryStr := strings.Repeat("0", shiftAmount) + binaryStr
resultBinary := paddedBinaryStr[:len(paddedBinaryStr)-shiftAmount]
return resultBinary
}
func main() {
text := "Rodolfo"
tToB := textToBinary(text)
fmt.Println(tToB)
nText := binaryToText(tToB)
fmt.Println(nText)
nToB := numberToBinary(2)
fmt.Println(nToB)
bToN := binaryToNumber(nToB)
fmt.Println(bToN)
afterLeftShift := leftShiftBinary(nToB, 1)
fmt.Println(afterLeftShift)
bToN2 := binaryToNumber(afterLeftShift)
fmt.Println(bToN2)
afterRightShift := rightShiftBinary(afterLeftShift, 1)
fmt.Println(afterRightShift)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment