numbers.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package serial
  2. import "strconv"
  3. func Uint16ToBytes(value uint16, b []byte) []byte {
  4. return append(b, byte(value>>8), byte(value))
  5. }
  6. func Uint16ToString(value uint16) string {
  7. return strconv.Itoa(int(value))
  8. }
  9. func WriteUint16(value uint16) func([]byte) (int, error) {
  10. return func(b []byte) (int, error) {
  11. b = Uint16ToBytes(value, b[:0])
  12. return 2, nil
  13. }
  14. }
  15. func Uint32ToBytes(value uint32, b []byte) []byte {
  16. return append(b, byte(value>>24), byte(value>>16), byte(value>>8), byte(value))
  17. }
  18. func Uint32ToString(value uint32) string {
  19. return strconv.FormatUint(uint64(value), 10)
  20. }
  21. func WriteUint32(value uint32) func([]byte) (int, error) {
  22. return func(b []byte) (int, error) {
  23. b = Uint32ToBytes(value, b[:0])
  24. return 4, nil
  25. }
  26. }
  27. func IntToBytes(value int, b []byte) []byte {
  28. return append(b, byte(value>>24), byte(value>>16), byte(value>>8), byte(value))
  29. }
  30. func IntToString(value int) string {
  31. return Int64ToString(int64(value))
  32. }
  33. func Int64ToBytes(value int64, b []byte) []byte {
  34. return append(b,
  35. byte(value>>56),
  36. byte(value>>48),
  37. byte(value>>40),
  38. byte(value>>32),
  39. byte(value>>24),
  40. byte(value>>16),
  41. byte(value>>8),
  42. byte(value))
  43. }
  44. func Int64ToString(value int64) string {
  45. return strconv.FormatInt(value, 10)
  46. }