You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

129 lines
2.1 KiB

  1. package util
  2. import (
  3. "crypto/md5"
  4. "encoding/base64"
  5. "fmt"
  6. "io"
  7. )
  8. // BytesToHumanReadable returns the converted human readable representation of the bytes.
  9. func BytesToHumanReadable(b uint64) string {
  10. const unit = 1024
  11. if b < unit {
  12. return fmt.Sprintf("%d B", b)
  13. }
  14. div, exp := uint64(unit), 0
  15. for n := b / unit; n >= unit; n /= unit {
  16. div *= unit
  17. exp++
  18. }
  19. return fmt.Sprintf("%.2f %ciB", float64(b)/float64(div), "KMGTPE"[exp])
  20. }
  21. // big endian
  22. func BytesToUint64(b []byte) (v uint64) {
  23. length := uint(len(b))
  24. for i := uint(0); i < length-1; i++ {
  25. v += uint64(b[i])
  26. v <<= 8
  27. }
  28. v += uint64(b[length-1])
  29. return
  30. }
  31. func BytesToUint32(b []byte) (v uint32) {
  32. length := uint(len(b))
  33. for i := uint(0); i < length-1; i++ {
  34. v += uint32(b[i])
  35. v <<= 8
  36. }
  37. v += uint32(b[length-1])
  38. return
  39. }
  40. func BytesToUint16(b []byte) (v uint16) {
  41. v += uint16(b[0])
  42. v <<= 8
  43. v += uint16(b[1])
  44. return
  45. }
  46. func Uint64toBytes(b []byte, v uint64) {
  47. for i := uint(0); i < 8; i++ {
  48. b[7-i] = byte(v >> (i * 8))
  49. }
  50. }
  51. func Uint32toBytes(b []byte, v uint32) {
  52. for i := uint(0); i < 4; i++ {
  53. b[3-i] = byte(v >> (i * 8))
  54. }
  55. }
  56. func Uint16toBytes(b []byte, v uint16) {
  57. b[0] = byte(v >> 8)
  58. b[1] = byte(v)
  59. }
  60. func Uint8toBytes(b []byte, v uint8) {
  61. b[0] = byte(v)
  62. }
  63. // returns a 64 bit big int
  64. func HashStringToLong(dir string) (v int64) {
  65. h := md5.New()
  66. io.WriteString(h, dir)
  67. b := h.Sum(nil)
  68. v += int64(b[0])
  69. v <<= 8
  70. v += int64(b[1])
  71. v <<= 8
  72. v += int64(b[2])
  73. v <<= 8
  74. v += int64(b[3])
  75. v <<= 8
  76. v += int64(b[4])
  77. v <<= 8
  78. v += int64(b[5])
  79. v <<= 8
  80. v += int64(b[6])
  81. v <<= 8
  82. v += int64(b[7])
  83. return
  84. }
  85. func HashToInt32(data []byte) (v int32) {
  86. h := md5.New()
  87. h.Write(data)
  88. b := h.Sum(nil)
  89. v += int32(b[0])
  90. v <<= 8
  91. v += int32(b[1])
  92. v <<= 8
  93. v += int32(b[2])
  94. v <<= 8
  95. v += int32(b[3])
  96. return
  97. }
  98. func Base64Encode(data []byte) string {
  99. return base64.StdEncoding.EncodeToString(data)
  100. }
  101. func Base64Md5(data []byte) string {
  102. hash := md5.New()
  103. hash.Write(data)
  104. return Base64Encode(hash.Sum(nil))
  105. }
  106. func Base64Md5ToBytes(contentMd5 string) []byte {
  107. data, err := base64.StdEncoding.DecodeString(contentMd5)
  108. if err != nil {
  109. return nil
  110. }
  111. return data
  112. }