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.

116 lines
1.9 KiB

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