Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript on nodejs represent timestamp in a 4 bytes array

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading