buffers


Examples of how to allocate a buffer, write in big or little endian format, encode to a hex string, and check if buffers are equal.

Node.js

  1. const buf = Buffer.alloc(6)
  2. let value = 0x1234567890ab
  3. let offset = 0
  4. let byteLength = 6
  5. buf.writeUIntBE(value, offset, byteLength)
  6. let hexstr = buf.toString('hex')
  7. console.log(hexstr)
  8. const buf2 = Buffer.alloc(6)
  9. value = 0x1234567890ab
  10. offset = 0
  11. byteLength = 6
  12. buf2.writeUIntLE(value, offset, byteLength)
  13. hexstr = buf2.toString('hex')
  14. console.log(hexstr)
  15. let isEqual = Buffer.compare(buf, buf2) === 0
  16. console.log(isEqual)
  17. isEqual = Buffer.compare(buf, buf) === 0
  18. console.log(isEqual)

Output

  1. 1234567890ab
  2. ab9078563412
  3. false
  4. true

Go

  1. package main
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "encoding/hex"
  6. "fmt"
  7. "log"
  8. "math/big"
  9. "reflect"
  10. )
  11. func writeUIntBE(buffer []byte, value, offset, byteLength int64) {
  12. slice := make([]byte, byteLength)
  13. val := new(big.Int)
  14. val.SetUint64(uint64(value))
  15. valBytes := val.Bytes()
  16. buf := bytes.NewBuffer(slice)
  17. err := binary.Write(buf, binary.BigEndian, &valBytes)
  18. if err != nil {
  19. log.Fatal(err)
  20. }
  21. slice = buf.Bytes()
  22. slice = slice[int64(len(slice))-byteLength : len(slice)]
  23. copy(buffer[offset:], slice)
  24. }
  25. func writeUIntLE(buffer []byte, value, offset, byteLength int64) {
  26. slice := make([]byte, byteLength)
  27. val := new(big.Int)
  28. val.SetUint64(uint64(value))
  29. valBytes := val.Bytes()
  30. tmp := make([]byte, len(valBytes))
  31. for i := range valBytes {
  32. tmp[i] = valBytes[len(valBytes)-1-i]
  33. }
  34. copy(slice, tmp)
  35. copy(buffer[offset:], slice)
  36. }
  37. func main() {
  38. buf := make([]byte, 6)
  39. writeUIntBE(buf, 0x1234567890ab, 0, 6)
  40. fmt.Println(hex.EncodeToString(buf))
  41. buf2 := make([]byte, 6)
  42. writeUIntLE(buf2, 0x1234567890ab, 0, 6)
  43. fmt.Println(hex.EncodeToString(buf2))
  44. isEqual := reflect.DeepEqual(buf, buf2)
  45. fmt.Println(isEqual)
  46. isEqual = reflect.DeepEqual(buf, buf)
  47. fmt.Println(isEqual)
  48. }

Output

  1. 1234567890ab
  2. ab9078563412
  3. false
  4. true