bytes.go 1.5 KB

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