How to convert BigEndian to LittleEndian and vice versa

Operations over multi-byte data types are not common and situations where you need to deal with them are not often. However when the time comes to deal with those types of data some helper functions could come into play. Below you could find all functions potentially needed in order to convert multi-byte data type representations known as BigEndian and LittleEndian:

function convertToBigEndian(val) {
  const buf = Buffer.allocUnsafe(4);

  return buf.writeUInt32BE(val, 0);
}

function convertToLittleEndian(val) {
  const buf = Buffer.allocUnsafe(4);

  return buf.writeUInt32LE(val, 0);
}

function convertToOtherEndian(val) {
  return Buffer.from(val).reverse();
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.