Home > Mobile >  javascript on nodejs represent timestamp in a 4 bytes array
javascript on nodejs represent timestamp in a 4 bytes array

Time:05-11

In order to work with an external API, I need to store in a 4 bytes array the current timestamp. I saw in their examples that the array should look for example:

[97, 91, 43, 83] // timestamp

How did they get to the above numbers? and how can I save in javascript (es6) with node.js the current timestamp into a 4 bytes array?

CodePudding user response:

A common timestamp metric is Unix time. The time I write this, the unix time is 1652213764, which in hexadecimal is 62 7a c8 04, which indeed can be represented with 4 bytes. The equivalent in decimal bytes is 98 122 200 4.

How to do this in JavaScript:

function timeStampBytes(timestamp) {
    const res = new Uint8Array(4);
    res[0] = timestamp >> 24;
    res[1] = (timestamp >> 16) & 0xff;
    res[2] = (timestamp >> 8) & 0xff;
    res[3] = timestamp & 0xff;
    return res;
}

let timestamp = Math.floor(Date.now() / 1000); // Unix time
console.log("timestamp: ", timestamp);
console.log("timestamp in HEX: ", timestamp.toString(16));
console.log("timestamp in bytes array: ", ...timeStampBytes(timestamp));

  • Related