numbers.go 1.3 KB

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