bytes.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package serial
  2. import "encoding/hex"
  3. // ByteToHexString converts a byte into hex string.
  4. func ByteToHexString(value byte) string {
  5. return hex.EncodeToString([]byte{value})
  6. }
  7. // BytesToUint16 deserializes a byte array to a uint16 in big endian order. The byte array must have at least 2 elements.
  8. func BytesToUint16(value []byte) uint16 {
  9. _ = value[1] // bounds check hint to compiler; see golang.org/issue/14808
  10. return uint16(value[0])<<8 | uint16(value[1])
  11. }
  12. // BytesToUint32 deserializes a byte array to a uint32 in big endian order. The byte array must have at least 4 elements.
  13. func BytesToUint32(value []byte) uint32 {
  14. _ = value[3]
  15. return uint32(value[0])<<24 |
  16. uint32(value[1])<<16 |
  17. uint32(value[2])<<8 |
  18. uint32(value[3])
  19. }
  20. // BytesToInt deserializes a bytes array (of at leat 4 bytes) to an int in big endian order.
  21. func BytesToInt(value []byte) int {
  22. _ = value[3]
  23. return int(value[0])<<24 |
  24. int(value[1])<<16 |
  25. int(value[2])<<8 |
  26. int(value[3])
  27. }
  28. // BytesToInt64 deserializes a byte array to an int64 in big endian order. The byte array must have at least 8 elements.
  29. func BytesToInt64(value []byte) int64 {
  30. _ = value[7]
  31. return int64(value[0])<<56 |
  32. int64(value[1])<<48 |
  33. int64(value[2])<<40 |
  34. int64(value[3])<<32 |
  35. int64(value[4])<<24 |
  36. int64(value[5])<<16 |
  37. int64(value[6])<<8 |
  38. int64(value[7])
  39. }
  40. // BytesToHexString converts a byte array into hex string.
  41. func BytesToHexString(value []byte) string {
  42. m := hex.EncodedLen(len(value))
  43. if m == 0 {
  44. return "[]"
  45. }
  46. n := 1 + m + m/2
  47. b := make([]byte, n)
  48. hex.Encode(b[1:], value)
  49. b[0] = '['
  50. for i, j := n-3, m-2+1; i > 0; i -= 3 {
  51. b[i+2] = ','
  52. b[i+1] = b[j+1]
  53. b[i] = b[j]
  54. j -= 2
  55. }
  56. b[n-1] = ']'
  57. return string(b)
  58. }