bytes.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 an uint16 in big endian order. The byte array must have at least 2 elements.
  8. func BytesToUint16(value []byte) uint16 {
  9. return uint16(value[0])<<8 | uint16(value[1])
  10. }
  11. // BytesToUint32 deserializes a byte array to an uint32 in big endian order. The byte array must have at least 4 elements.
  12. func BytesToUint32(value []byte) uint32 {
  13. return uint32(value[0])<<24 |
  14. uint32(value[1])<<16 |
  15. uint32(value[2])<<8 |
  16. uint32(value[3])
  17. }
  18. // BytesToInt64 deserializes a byte array to an int64 in big endian order. The byte array must have at least 8 elements.
  19. func BytesToInt64(value []byte) int64 {
  20. return int64(value[0])<<56 |
  21. int64(value[1])<<48 |
  22. int64(value[2])<<40 |
  23. int64(value[3])<<32 |
  24. int64(value[4])<<24 |
  25. int64(value[5])<<16 |
  26. int64(value[6])<<8 |
  27. int64(value[7])
  28. }
  29. // BytesToHexString converts a byte array into hex string.
  30. func BytesToHexString(value []byte) string {
  31. m := hex.EncodedLen(len(value))
  32. if m == 0 {
  33. return "[]"
  34. }
  35. n := 1 + m + m/2
  36. b := make([]byte, n)
  37. hex.Encode(b[1:], value)
  38. b[0] = '['
  39. for i, j := n-3, m-2+1; i > 0; i -= 3 {
  40. b[i+2] = ','
  41. b[i+1] = b[j+1]
  42. b[i] = b[j]
  43. j -= 2
  44. }
  45. b[n-1] = ']'
  46. return string(b)
  47. }