numbers.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 WriteUint16(value uint16) func([]byte) (int, error) {
  19. return func(b []byte) (int, error) {
  20. Uint16ToBytes(value, b[:0])
  21. return 2, nil
  22. }
  23. }
  24. func Uint32ToBytes(value uint32, b []byte) []byte {
  25. return append(b, byte(value>>24), byte(value>>16), byte(value>>8), byte(value))
  26. }
  27. func Uint32ToString(value uint32) string {
  28. return strconv.FormatUint(uint64(value), 10)
  29. }
  30. func WriteUint32(value uint32) func([]byte) (int, error) {
  31. return func(b []byte) (int, error) {
  32. Uint32ToBytes(value, b[:0])
  33. return 4, nil
  34. }
  35. }
  36. func IntToBytes(value int, b []byte) []byte {
  37. return append(b, byte(value>>24), byte(value>>16), byte(value>>8), byte(value))
  38. }
  39. func IntToString(value int) string {
  40. return Int64ToString(int64(value))
  41. }
  42. func Int64ToBytes(value int64, b []byte) []byte {
  43. return append(b,
  44. byte(value>>56),
  45. byte(value>>48),
  46. byte(value>>40),
  47. byte(value>>32),
  48. byte(value>>24),
  49. byte(value>>16),
  50. byte(value>>8),
  51. byte(value))
  52. }
  53. func Int64ToString(value int64) string {
  54. return strconv.FormatInt(value, 10)
  55. }