numbers.go 1.3 KB

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