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.

100 lines
1.5 KiB

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