diff --git a/format.go b/format.go new file mode 100644 index 0000000..b5b896a --- /dev/null +++ b/format.go @@ -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 "<>" + } + + + var output bytes.Buffer + + length := buffer.Len() + for i:=0; i>") + + return output.String() +} diff --git a/format_test.go b/format_test.go new file mode 100644 index 0000000..717bf8b --- /dev/null +++ b/format_test.go @@ -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 + + } + } +}