util.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package utils
  2. import (
  3. "bytes"
  4. "dlt645-server/errors"
  5. "time"
  6. )
  7. // bytes切割
  8. func BytesSplit(data []byte, limit int) [][]byte {
  9. var chunk []byte
  10. chunks := make([][]byte, 0, len(data)/limit+1)
  11. for len(data) >= limit {
  12. chunk, data = data[:limit], data[limit:]
  13. chunks = append(chunks, chunk)
  14. }
  15. if len(data) > 0 {
  16. chunks = append(chunks, data[:len(data)])
  17. }
  18. return chunks
  19. }
  20. // bytes转字符串
  21. func BytesToString(data []byte) string {
  22. n := bytes.IndexByte(data, 0)
  23. if n == -1 {
  24. return string(data)
  25. }
  26. return string(data[:n])
  27. }
  28. // 字符串转BCD
  29. func StringToBCD(s string, size ...int) []byte {
  30. if (len(s) & 1) != 0 {
  31. s = "0" + s
  32. }
  33. data := []byte(s)
  34. bcd := make([]byte, len(s)/2)
  35. for i := 0; i < len(bcd); i++ {
  36. high := data[i*2] - '0'
  37. low := data[i*2+1] - '0'
  38. bcd[i] = (high << 4) | low
  39. }
  40. if len(size) == 0 {
  41. return bcd
  42. }
  43. ret := make([]byte, size[0])
  44. if size[0] < len(bcd) {
  45. copy(ret, bcd)
  46. } else {
  47. copy(ret[len(ret)-len(bcd):], bcd)
  48. }
  49. return ret
  50. }
  51. // BCD转字符串
  52. func BcdToString(data []byte, ignorePadding ...bool) string {
  53. for {
  54. if len(data) == 0 {
  55. return ""
  56. }
  57. if data[0] != 0 {
  58. break
  59. }
  60. data = data[1:]
  61. }
  62. buf := make([]byte, 0, len(data)*2)
  63. for i := 0; i < len(data); i++ {
  64. buf = append(buf, data[i]&0xf0>>4+'0')
  65. buf = append(buf, data[i]&0x0f+'0')
  66. }
  67. if len(ignorePadding) == 0 || !ignorePadding[0] {
  68. for idx := range buf {
  69. if buf[idx] != '0' {
  70. return string(buf[idx:])
  71. }
  72. }
  73. }
  74. return string(buf)
  75. }
  76. // 转为BCD时间
  77. func ToBCDTime(t time.Time) []byte {
  78. t = time.Unix(t.Unix(), 0)
  79. s := t.Format("20060102150405")[2:]
  80. return StringToBCD(s, 6)
  81. }
  82. // 转为time.Time
  83. func FromBCDTime(bcd []byte) (time.Time, error) {
  84. if len(bcd) != 6 {
  85. return time.Time{}, errors.ErrInvalidBCDTime
  86. }
  87. t, err := time.ParseInLocation(
  88. "20060102150405", "20"+BcdToString(bcd), time.Local)
  89. if err != nil {
  90. return time.Time{}, err
  91. }
  92. return t, nil
  93. }