bytes.go 1.6 KB

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