utf8s.FormatBinary()

master
Charles Iliya Krempeaux 2018-07-01 23:27:20 -07:00
parent 4baaa99b2b
commit d4b29542cb
2 changed files with 171 additions and 0 deletions

98
format.go 100644
View File

@ -0,0 +1,98 @@
package utf8s
import (
"bytes"
)
// FormatBinary returns a representation of a rune as a sequence of bytes, given in binary format.
//
// Example
//
// utf8s.FormatBinary('۵')
//
// // Outputs:
// // <<0b11011011 ; 0b10110101>>
func FormatBinary(r rune) string {
var buffer bytes.Buffer
_, err := WriteRune(&buffer, r)
if nil != err {
return "<<ERROR>>"
}
var output bytes.Buffer
length := buffer.Len()
for i:=0; i<length; i++ {
switch i {
case 0:
output.WriteString("<<0b")
default:
output.WriteString(" ; 0b")
}
b := buffer.Bytes()[i]
switch {
case 0 == (0x80 & b):
output.WriteRune('0')
default:
output.WriteRune('1')
}
switch {
case 0 == (0x40 & b):
output.WriteRune('0')
default:
output.WriteRune('1')
}
switch {
case 0 == (0x20 & b):
output.WriteRune('0')
default:
output.WriteRune('1')
}
switch {
case 0 == (0x10 & b):
output.WriteRune('0')
default:
output.WriteRune('1')
}
switch {
case 0 == (0x08 & b):
output.WriteRune('0')
default:
output.WriteRune('1')
}
switch {
case 0 == (0x04 & b):
output.WriteRune('0')
default:
output.WriteRune('1')
}
switch {
case 0 == (0x02 & b):
output.WriteRune('0')
default:
output.WriteRune('1')
}
switch {
case 0 == (0x01 & b):
output.WriteRune('0')
default:
output.WriteRune('1')
}
}
output.WriteString(">>")
return output.String()
}

73
format_test.go 100644
View File

@ -0,0 +1,73 @@
package utf8s
import (
"testing"
)
func TestFormatBinary(t *testing.T) {
tests := []struct{
Rune rune
Expected string
}{
{
Rune: 'A',
Expected: "<<0b01000001>>",
},
{
Rune: 'r',
Expected: "<<0b01110010>>",
},
{
Rune: '¡',
Expected: "<<0b11000010 ; 0b10100001>>",
},
{
Rune: '۵',
Expected: "<<0b11011011 ; 0b10110101>>",
},
{
Rune: '‱',
Expected: "<<0b11100010 ; 0b10000000 ; 0b10110001>>",
},
{
Rune: '≡',
Expected: "<<0b11100010 ; 0b10001001 ; 0b10100001>>",
},
{
Rune: '🙂',
Expected: "<<0b11110000 ; 0b10011111 ; 0b10011001 ; 0b10000010>>",
},
}
for testNumber, test := range tests {
actual := FormatBinary(test.Rune)
if expected := test.Expected; expected != actual {
t.Errorf("For test #%d, expected %q, but actually got %q.", testNumber, expected, actual)
t.Errorf("\trune = %q (%X)", test.Rune, test.Rune)
continue
}
}
}