v2ray-core/common/serial/bytes.go

62 lines
1.6 KiB
Go
Raw Normal View History

2015-12-12 12:11:49 +00:00
package serial
2017-04-26 21:26:42 +00:00
import "encoding/hex"
2016-01-29 09:57:52 +00:00
2017-04-26 21:26:42 +00:00
// ByteToHexString converts a byte into hex string.
2016-05-24 19:55:46 +00:00
func ByteToHexString(value byte) string {
return hex.EncodeToString([]byte{value})
}
2017-02-13 21:39:55 +00:00
// BytesToUint16 deserializes a byte array to an uint16 in big endian order. The byte array must have at least 2 elements.
2016-05-24 19:55:46 +00:00
func BytesToUint16(value []byte) uint16 {
2016-06-26 20:34:48 +00:00
return uint16(value[0])<<8 | uint16(value[1])
2016-05-24 19:55:46 +00:00
}
2017-02-13 21:39:55 +00:00
// BytesToUint32 deserializes a byte array to an uint32 in big endian order. The byte array must have at least 4 elements.
2016-05-24 20:09:22 +00:00
func BytesToUint32(value []byte) uint32 {
2016-06-26 20:34:48 +00:00
return uint32(value[0])<<24 |
uint32(value[1])<<16 |
uint32(value[2])<<8 |
2016-01-22 16:56:03 +00:00
uint32(value[3])
}
2017-08-24 21:10:58 +00:00
// BytesToInt deserializes a bytes array (of at leat 4 bytes) to an int in big endian order.
2017-04-30 21:37:30 +00:00
func BytesToInt(value []byte) int {
return int(value[0])<<24 |
int(value[1])<<16 |
int(value[2])<<8 |
int(value[3])
}
2017-02-13 21:39:55 +00: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 20:09:22 +00:00
func BytesToInt64(value []byte) int64 {
2016-06-26 20:34:48 +00: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 12:11:49 +00:00
int64(value[7])
}
2016-01-18 11:58:04 +00:00
2017-04-26 21:26:42 +00:00
// BytesToHexString converts a byte array into hex string.
2016-05-24 20:09:22 +00:00
func BytesToHexString(value []byte) string {
2017-04-26 21:26:42 +00:00
m := hex.EncodedLen(len(value))
if m == 0 {
return "[]"
2016-01-21 12:05:16 +00:00
}
2017-04-26 21:26:42 +00: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 12:05:16 +00:00
}