Created
April 14, 2022 12:27
-
-
Save hsnks100/93ce8e5701f20aeebf05eba547fad238 to your computer and use it in GitHub Desktop.
golang snif
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"encoding/binary" | |
"encoding/hex" | |
"fmt" | |
) | |
func uintToLittleEndian(u uint64, b int) []byte { | |
buff := new(bytes.Buffer) | |
_ = binary.Write(buff, binary.LittleEndian, u) | |
// 0x11 0x22 | |
// 0x22 0x11 0x00 0x00 0x00 | |
// 0x | |
return buff.Bytes()[:b] | |
} | |
func uintToBigEndian(u uint64, b int) []byte { | |
buff := new(bytes.Buffer) | |
_ = binary.Write(buff, binary.BigEndian, u) | |
// 0x11 0x22 | |
// 0x22 0x11 0x00 0x00 0x00 | |
// 0x | |
return buff.Bytes()[8-b:] | |
} | |
func BigEndianToInt(b2 []byte) uint64 { | |
b := make([]byte, len(b2)) | |
copy(b, b2) | |
n := 8 - len(b) | |
for i := 0; i < n; i++ { | |
b = append([]byte{0x00}, b...) | |
} | |
data := binary.BigEndian.Uint64(b) | |
return data | |
} | |
func LittleEndianToInt(b2 []byte) uint64 { | |
b := make([]byte, len(b2)) | |
copy(b, b2) | |
n := 8 - len(b) | |
for i := 0; i < n; i++ { | |
b = append(b, 0x00) | |
} | |
data := binary.LittleEndian.Uint64(b) | |
return data | |
} | |
func main() { | |
fmt.Println(hex.Dump(uintToLittleEndian(0x1122, 5))) | |
fmt.Println(hex.Dump(uintToBigEndian(0x1122, 3))) | |
fmt.Println(BigEndianToInt([]byte{0x11, 0x12, 0x13})) | |
fmt.Println(LittleEndianToInt([]byte{0x11, 0x12, 0x13})) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment