bytes.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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 IsHex(str string) bool {
  111. l := len(str)
  112. return l >= 4 && l%2 == 0 && str[0:2] == "0x"
  113. }
  114. func Bytes2Hex(d []byte) string {
  115. return hex.EncodeToString(d)
  116. }
  117. func Hex2Bytes(str string) []byte {
  118. h, _ := hex.DecodeString(str)
  119. return h
  120. }
  121. func StringToByteFunc(str string, cb func(str string) []byte) (ret []byte) {
  122. if len(str) > 1 && str[0:2] == "0x" && !strings.Contains(str, "\n") {
  123. ret = Hex2Bytes(str[2:])
  124. } else {
  125. ret = cb(str)
  126. }
  127. return
  128. }
  129. func FormatData(data string) []byte {
  130. if len(data) == 0 {
  131. return nil
  132. }
  133. // Simple stupid
  134. d := new(big.Int)
  135. if data[0:1] == "\"" && data[len(data)-1:] == "\"" {
  136. return RightPadBytes([]byte(data[1:len(data)-1]), 32)
  137. } else if len(data) > 1 && data[:2] == "0x" {
  138. d.SetBytes(Hex2Bytes(data[2:]))
  139. } else {
  140. d.SetString(data, 0)
  141. }
  142. return BigToBytes(d, 256)
  143. }
  144. func ParseData(data ...interface{}) (ret []byte) {
  145. for _, item := range data {
  146. switch t := item.(type) {
  147. case string:
  148. var str []byte
  149. if IsHex(t) {
  150. str = Hex2Bytes(t[2:])
  151. } else {
  152. str = []byte(t)
  153. }
  154. ret = append(ret, RightPadBytes(str, 32)...)
  155. case []byte:
  156. ret = append(ret, LeftPadBytes(t, 32)...)
  157. }
  158. }
  159. return
  160. }
  161. func RightPadBytes(slice []byte, l int) []byte {
  162. if l < len(slice) {
  163. return slice
  164. }
  165. padded := make([]byte, l)
  166. copy(padded[0:len(slice)], slice)
  167. return padded
  168. }
  169. func LeftPadBytes(slice []byte, l int) []byte {
  170. if l < len(slice) {
  171. return slice
  172. }
  173. padded := make([]byte, l)
  174. copy(padded[l-len(slice):], slice)
  175. return padded
  176. }
  177. func LeftPadString(str string, l int) string {
  178. if l < len(str) {
  179. return str
  180. }
  181. zeros := Bytes2Hex(make([]byte, (l-len(str))/2))
  182. return zeros + str
  183. }
  184. func RightPadString(str string, l int) string {
  185. if l < len(str) {
  186. return str
  187. }
  188. zeros := Bytes2Hex(make([]byte, (l-len(str))/2))
  189. return str + zeros
  190. }
  191. func ToAddress(slice []byte) (addr []byte) {
  192. if len(slice) < 20 {
  193. addr = LeftPadBytes(slice, 20)
  194. } else if len(slice) > 20 {
  195. addr = slice[len(slice)-20:]
  196. } else {
  197. addr = slice
  198. }
  199. addr = CopyBytes(addr)
  200. return
  201. }
  202. func ByteSliceToInterface(slice [][]byte) (ret []interface{}) {
  203. for _, i := range slice {
  204. ret = append(ret, i)
  205. }
  206. return
  207. }