bits_test.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package bits
  2. import (
  3. "bytes"
  4. "testing"
  5. )
  6. func TestBits(t *testing.T) {
  7. rdata := []byte{0xf3, 0xb3, 0x45, 0x60}
  8. rbuf := bytes.NewReader(rdata[:])
  9. r := &Reader{R: rbuf}
  10. var u32 uint
  11. if u32, _ = r.ReadBits(4); u32 != 0xf {
  12. t.FailNow()
  13. }
  14. if u32, _ = r.ReadBits(4); u32 != 0x3 {
  15. t.FailNow()
  16. }
  17. if u32, _ = r.ReadBits(2); u32 != 0x2 {
  18. t.FailNow()
  19. }
  20. if u32, _ = r.ReadBits(2); u32 != 0x3 {
  21. t.FailNow()
  22. }
  23. b := make([]byte, 2)
  24. if r.Read(b); b[0] != 0x34 || b[1] != 0x56 {
  25. t.FailNow()
  26. }
  27. wbuf := &bytes.Buffer{}
  28. w := &Writer{W: wbuf}
  29. w.WriteBits(0xf, 4)
  30. w.WriteBits(0x3, 4)
  31. w.WriteBits(0x2, 2)
  32. w.WriteBits(0x3, 2)
  33. n, _ := w.Write([]byte{0x34, 0x56})
  34. if n != 2 {
  35. t.FailNow()
  36. }
  37. w.FlushBits()
  38. wdata := wbuf.Bytes()
  39. if wdata[0] != 0xf3 || wdata[1] != 0xb3 || wdata[2] != 0x45 || wdata[3] != 0x60 {
  40. t.FailNow()
  41. }
  42. b = make([]byte, 8)
  43. PutUInt64BE(b, 0x11223344)
  44. if b[0] != 0x11 || b[1] != 0x22 || b[2] != 0x33 || b[3] != 0x44 {
  45. t.FailNow()
  46. }
  47. }
  48. func PutUInt64BE(b []byte, v uint64) {
  49. b[0] = byte(v >> 56)
  50. b[1] = byte(v >> 48)
  51. b[2] = byte(v >> 40)
  52. b[3] = byte(v >> 32)
  53. b[4] = byte(v >> 24)
  54. b[5] = byte(v >> 16)
  55. b[6] = byte(v >> 8)
  56. b[7] = byte(v)
  57. }