bytes.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package serial
  2. import (
  3. "bytes"
  4. "encoding/hex"
  5. "strings"
  6. )
  7. func ByteToHexString(value byte) string {
  8. return hex.EncodeToString([]byte{value})
  9. }
  10. func BytesToUint16(value []byte) uint16 {
  11. return uint16(value[0])<<8 + uint16(value[1])
  12. }
  13. func BytesToHexString(value []byte) string {
  14. strs := make([]string, len(value))
  15. for i, b := range value {
  16. strs[i] = hex.EncodeToString([]byte{b})
  17. }
  18. return "[" + strings.Join(strs, ",") + "]"
  19. }
  20. type BytesT []byte
  21. func (this BytesT) Value() []byte {
  22. return []byte(this)
  23. }
  24. func (this BytesT) Equals(another BytesT) bool {
  25. return bytes.Equal(this.Value(), another.Value())
  26. }
  27. func (this BytesT) Uint8Value() uint8 {
  28. return this.Value()[0]
  29. }
  30. func (this BytesT) Uint16() Uint16Literal {
  31. return Uint16Literal(this.Uint16Value())
  32. }
  33. func (this BytesT) Uint16Value() uint16 {
  34. value := this.Value()
  35. return uint16(value[0])<<8 + uint16(value[1])
  36. }
  37. func (this BytesT) IntValue() int {
  38. value := this.Value()
  39. return int(value[0])<<24 + int(value[1])<<16 + int(value[2])<<8 + int(value[3])
  40. }
  41. func (this BytesT) Uint32Value() uint32 {
  42. value := this.Value()
  43. return uint32(value[0])<<24 +
  44. uint32(value[1])<<16 +
  45. uint32(value[2])<<8 +
  46. uint32(value[3])
  47. }
  48. func (this BytesT) Int64Value() int64 {
  49. value := this.Value()
  50. return int64(value[0])<<56 +
  51. int64(value[1])<<48 +
  52. int64(value[2])<<40 +
  53. int64(value[3])<<32 +
  54. int64(value[4])<<24 +
  55. int64(value[5])<<16 +
  56. int64(value[6])<<8 +
  57. int64(value[7])
  58. }
  59. // String returns a string presentation of this ByteLiteral
  60. func (this BytesT) String() string {
  61. return string(this.Value())
  62. }
  63. // All returns true if all bytes in the ByteLiteral are the same as given value.
  64. func (this BytesT) All(v byte) bool {
  65. for _, b := range this {
  66. if b != v {
  67. return false
  68. }
  69. }
  70. return true
  71. }