bytes.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. package common
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "encoding/hex"
  6. "fmt"
  7. "math/big"
  8. "strings"
  9. )
  10. func ToHex(b []byte) string {
  11. hex := Bytes2Hex(b)
  12. // Prefer output of "0x0" instead of "0x"
  13. if len(hex) == 0 {
  14. hex = "0"
  15. }
  16. return "0x" + hex
  17. }
  18. func FromHex(s string) []byte {
  19. if len(s) > 1 {
  20. if s[0:2] == "0x" {
  21. s = s[2:]
  22. }
  23. if len(s)%2 == 1 {
  24. s = "0" + s
  25. }
  26. return Hex2Bytes(s)
  27. }
  28. return nil
  29. }
  30. type Bytes []byte
  31. func (self Bytes) String() string {
  32. return string(self)
  33. }
  34. func DeleteFromByteSlice(s [][]byte, hash []byte) [][]byte {
  35. for i, h := range s {
  36. if bytes.Compare(h, hash) == 0 {
  37. return append(s[:i:i], s[i+1:]...)
  38. }
  39. }
  40. return s
  41. }
  42. // Number to bytes
  43. //
  44. // Returns the number in bytes with the specified base
  45. func NumberToBytes(num interface{}, bits int) []byte {
  46. buf := new(bytes.Buffer)
  47. err := binary.Write(buf, binary.BigEndian, num)
  48. if err != nil {
  49. fmt.Println("NumberToBytes failed:", err)
  50. }
  51. return buf.Bytes()[buf.Len()-(bits/8):]
  52. }
  53. // Bytes to number
  54. //
  55. // Attempts to cast a byte slice to a unsigned integer
  56. func BytesToNumber(b []byte) uint64 {
  57. var number uint64
  58. // Make sure the buffer is 64bits
  59. data := make([]byte, 8)
  60. data = append(data[:len(b)], b...)
  61. buf := bytes.NewReader(data)
  62. err := binary.Read(buf, binary.BigEndian, &number)
  63. if err != nil {
  64. fmt.Println("BytesToNumber failed:", err)
  65. }
  66. return number
  67. }
  68. // Read variable int
  69. //
  70. // Read a variable length number in big endian byte order
  71. func ReadVarInt(buff []byte) (ret uint64) {
  72. switch l := len(buff); {
  73. case l > 4:
  74. d := LeftPadBytes(buff, 8)
  75. binary.Read(bytes.NewReader(d), binary.BigEndian, &ret)
  76. case l > 2:
  77. var num uint32
  78. d := LeftPadBytes(buff, 4)
  79. binary.Read(bytes.NewReader(d), binary.BigEndian, &num)
  80. ret = uint64(num)
  81. case l > 1:
  82. var num uint16
  83. d := LeftPadBytes(buff, 2)
  84. binary.Read(bytes.NewReader(d), binary.BigEndian, &num)
  85. ret = uint64(num)
  86. default:
  87. var num uint8
  88. binary.Read(bytes.NewReader(buff), binary.BigEndian, &num)
  89. ret = uint64(num)
  90. }
  91. return
  92. }
  93. // Binary length
  94. //
  95. // Returns the true binary length of the given number
  96. func BinaryLength(num int) int {
  97. if num == 0 {
  98. return 0
  99. }
  100. return 1 + BinaryLength(num>>8)
  101. }
  102. // Copy bytes
  103. //
  104. // Returns an exact copy of the provided bytes
  105. func CopyBytes(b []byte) (copiedBytes []byte) {
  106. copiedBytes = make([]byte, len(b))
  107. copy(copiedBytes, b)
  108. return
  109. }
  110. func HasHexPrefix(str string) bool {
  111. l := len(str)
  112. return l >= 2 && str[0:2] == "0x"
  113. }
  114. func IsHex(str string) bool {
  115. l := len(str)
  116. return l >= 4 && l%2 == 0 && str[0:2] == "0x"
  117. }
  118. func Bytes2Hex(d []byte) string {
  119. return hex.EncodeToString(d)
  120. }
  121. func Hex2Bytes(str string) []byte {
  122. h, _ := hex.DecodeString(str)
  123. return h
  124. }
  125. func Hex2BytesFixed(str string, flen int) []byte {
  126. h, _ := hex.DecodeString(str)
  127. if len(h) == flen {
  128. return h
  129. } else {
  130. if len(h) > flen {
  131. return h[len(h)-flen : len(h)]
  132. } else {
  133. hh := make([]byte, flen)
  134. copy(hh[flen-len(h):flen], h[:])
  135. return hh
  136. }
  137. }
  138. }
  139. func StringToByteFunc(str string, cb func(str string) []byte) (ret []byte) {
  140. if len(str) > 1 && str[0:2] == "0x" && !strings.Contains(str, "\n") {
  141. ret = Hex2Bytes(str[2:])
  142. } else {
  143. ret = cb(str)
  144. }
  145. return
  146. }
  147. func FormatData(data string) []byte {
  148. if len(data) == 0 {
  149. return nil
  150. }
  151. // Simple stupid
  152. d := new(big.Int)
  153. if data[0:1] == "\"" && data[len(data)-1:] == "\"" {
  154. return RightPadBytes([]byte(data[1:len(data)-1]), 32)
  155. } else if len(data) > 1 && data[:2] == "0x" {
  156. d.SetBytes(Hex2Bytes(data[2:]))
  157. } else {
  158. d.SetString(data, 0)
  159. }
  160. return BigToBytes(d, 256)
  161. }
  162. func ParseData(data ...interface{}) (ret []byte) {
  163. for _, item := range data {
  164. switch t := item.(type) {
  165. case string:
  166. var str []byte
  167. if IsHex(t) {
  168. str = Hex2Bytes(t[2:])
  169. } else {
  170. str = []byte(t)
  171. }
  172. ret = append(ret, RightPadBytes(str, 32)...)
  173. case []byte:
  174. ret = append(ret, LeftPadBytes(t, 32)...)
  175. }
  176. }
  177. return
  178. }
  179. func RightPadBytes(slice []byte, l int) []byte {
  180. if l < len(slice) {
  181. return slice
  182. }
  183. padded := make([]byte, l)
  184. copy(padded[0:len(slice)], slice)
  185. return padded
  186. }
  187. func LeftPadBytes(slice []byte, l int) []byte {
  188. if l < len(slice) {
  189. return slice
  190. }
  191. padded := make([]byte, l)
  192. copy(padded[l-len(slice):], slice)
  193. return padded
  194. }
  195. func LeftPadString(str string, l int) string {
  196. if l < len(str) {
  197. return str
  198. }
  199. zeros := Bytes2Hex(make([]byte, (l-len(str))/2))
  200. return zeros + str
  201. }
  202. func RightPadString(str string, l int) string {
  203. if l < len(str) {
  204. return str
  205. }
  206. zeros := Bytes2Hex(make([]byte, (l-len(str))/2))
  207. return str + zeros
  208. }
  209. func ToAddress(slice []byte) (addr []byte) {
  210. if len(slice) < 20 {
  211. addr = LeftPadBytes(slice, 20)
  212. } else if len(slice) > 20 {
  213. addr = slice[len(slice)-20:]
  214. } else {
  215. addr = slice
  216. }
  217. addr = CopyBytes(addr)
  218. return
  219. }
  220. func ByteSliceToInterface(slice [][]byte) (ret []interface{}) {
  221. for _, i := range slice {
  222. ret = append(ret, i)
  223. }
  224. return
  225. }