1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-17 18:06:15 -05:00
v2fly/common/serial/bytes.go

66 lines
1.7 KiB
Go
Raw Normal View History

2015-12-12 07:11:49 -05:00
package serial
2017-04-26 17:26:42 -04:00
import "encoding/hex"
2016-01-29 04:57:52 -05:00
2017-04-26 17:26:42 -04:00
// ByteToHexString converts a byte into hex string.
2016-05-24 15:55:46 -04:00
func ByteToHexString(value byte) string {
return hex.EncodeToString([]byte{value})
}
2018-04-02 03:52:16 -04:00
// BytesToUint16 deserializes a byte array to a uint16 in big endian order. The byte array must have at least 2 elements.
2016-05-24 15:55:46 -04:00
func BytesToUint16(value []byte) uint16 {
_ = value[1] // bounds check hint to compiler; see golang.org/issue/14808
2016-06-26 16:34:48 -04:00
return uint16(value[0])<<8 | uint16(value[1])
2016-05-24 15:55:46 -04:00
}
2018-04-02 03:52:16 -04:00
// BytesToUint32 deserializes a byte array to a uint32 in big endian order. The byte array must have at least 4 elements.
2016-05-24 16:09:22 -04:00
func BytesToUint32(value []byte) uint32 {
_ = value[3]
2016-06-26 16:34:48 -04:00
return uint32(value[0])<<24 |
uint32(value[1])<<16 |
uint32(value[2])<<8 |
2016-01-22 11:56:03 -05:00
uint32(value[3])
}
2017-08-24 17:10:58 -04:00
// BytesToInt deserializes a bytes array (of at leat 4 bytes) to an int in big endian order.
2017-04-30 17:37:30 -04:00
func BytesToInt(value []byte) int {
_ = value[3]
2017-04-30 17:37:30 -04:00
return int(value[0])<<24 |
int(value[1])<<16 |
int(value[2])<<8 |
int(value[3])
}
2017-02-13 16:39:55 -05:00
// BytesToInt64 deserializes a byte array to an int64 in big endian order. The byte array must have at least 8 elements.
2016-05-24 16:09:22 -04:00
func BytesToInt64(value []byte) int64 {
_ = value[7]
2016-06-26 16:34:48 -04:00
return int64(value[0])<<56 |
int64(value[1])<<48 |
int64(value[2])<<40 |
int64(value[3])<<32 |
int64(value[4])<<24 |
int64(value[5])<<16 |
int64(value[6])<<8 |
2015-12-12 07:11:49 -05:00
int64(value[7])
}
2016-01-18 06:58:04 -05:00
2017-04-26 17:26:42 -04:00
// BytesToHexString converts a byte array into hex string.
2016-05-24 16:09:22 -04:00
func BytesToHexString(value []byte) string {
2017-04-26 17:26:42 -04:00
m := hex.EncodedLen(len(value))
if m == 0 {
return "[]"
2016-01-21 07:05:16 -05:00
}
2017-04-26 17:26:42 -04:00
n := 1 + m + m/2
b := make([]byte, n)
hex.Encode(b[1:], value)
b[0] = '['
for i, j := n-3, m-2+1; i > 0; i -= 3 {
b[i+2] = ','
b[i+1] = b[j+1]
b[i] = b[j]
j -= 2
}
b[n-1] = ']'
return string(b)
2016-01-21 07:05:16 -05:00
}