John Henry John Henry - 4 months ago 23
Javascript Question

How does one increment a buffer?

I have a large number represented as a hexadecimal string.
I need to convert it to a buffer, and make use of it.
Then, I need to increment said number (now a buffer) by 1 continuously, and make more use of it.

Is there a way to simply add 1 to a buffer?
If not, would it make sense to manually create a new buffer by incrementing the numbers from right to left? Does it make more sense to attempt to use a third-party library to add to the original hexadecimal string and then re-convert it every time?

Thanks!

Answer

These functions should allow you to increment the buffer. You only have to chose if you want big or little endian.

/**
 * @summary increment a buffer in little endian
 * @param buffer {Buffer} input buffer, will be modified
 * @description
 * Since 255 + 1 = 0 (mod 256), a "carry" is needed, if the
 * element is 255 before incrementing
 */
function incrementLE (buffer) {
    for (var i = 0; i < buffer.length; i++) {
        if (buffer[i]++ !== 255) break;
    }
}

/**
 * @summary increment a buffer in big endian
 */
function incrementBE (buffer) {
    for (var i = buffer.length - 1; i >= 0; i--) {
        if (buffer[i]++ !== 255) break;
    }
}
Comments