big_endian.go 546 B

12345678910111213141516171819202122232425262728
  1. package util
  2. type Integer interface {
  3. ~int | ~int16 | ~int32 | ~int64 | ~uint | ~uint16 | ~uint32 | ~uint64
  4. }
  5. func PutBE[T Integer](b []byte, num T) []byte {
  6. for i, n := 0, len(b); i < n; i++ {
  7. b[i] = byte(num >> ((n - i - 1) << 3))
  8. }
  9. return b
  10. }
  11. func ReadBE[T Integer](b []byte) (num T) {
  12. num = 0
  13. for i, n := 0, len(b); i < n; i++ {
  14. num += T(b[i]) << ((n - i - 1) << 3)
  15. }
  16. return
  17. }
  18. func GetBE[T Integer](b []byte, num *T) T {
  19. *num = 0
  20. for i, n := 0, len(b); i < n; i++ {
  21. *num += T(b[i]) << ((n - i - 1) << 3)
  22. }
  23. return *num
  24. }