function generateCRC16(payload) {
    let crc = 0xFFFF;
    for (let i = 0; i < payload.length; i++) {
        let c = payload.charCodeAt(i);
        crc ^= (c << 8);
        for (let j = 0; j < 8; j++) {
            if ((crc & 0x8000) !== 0) {
                crc = (crc << 1) ^ 0x1021;
            } else {
                crc = crc << 1;
            }
        }
        // Force 16-bit behavior for JS integers
        crc = crc & 0xFFFF; 
    }
    return crc.toString(16).toUpperCase().padStart(4, '0');
}

// Previous implementation to check if it matches the user's output
function generateCRC16_Old(payload) {
    let crc = 0xFFFF;
    for (let i = 0; i < payload.length; i++) {
        let c = payload.charCodeAt(i);
        crc ^= (c << 8);
        for (let j = 0; j < 8; j++) {
            if ((crc & 0x8000) !== 0) {
                crc = (crc << 1) ^ 0x1021;
            } else {
                crc = crc << 1;
            }
        }
    }
    return (crc & 0xFFFF).toString(16).toUpperCase().padStart(4, '0');
}

const payload = "00020126330014br.gov.bcb.pix0111119615342255204000053039865802BR5916Ricardo Carneiro6012Sao Bernardo62070503***6304";
console.log("Payload:", payload);
console.log("CRC New (Masked):", generateCRC16(payload));
console.log("CRC Old (Original):", generateCRC16_Old(payload));
console.log("User Reported CRC:", "B716");
