Search code examples
actionscript-3as3crypto

AS3 Calculate Longitudinal Redundancy Check (LRC) - Socket


I need to send to the socket:

<STX>PIPE_DELIMITED_MESSAGE<ETX><LRC>

STX = String.fromCharCode(02) //// **Good**
ETX­ = String.fromCharCode(03) //// **Good**
LRC = Unable to calculate correctly

Request: LRC is the result of 8­bit EXCLUSIVE­ OR (Binary ADD without Carry) of all bytes starting with the byte after STX and including the final ETX of the message.

I was using below, but is not correct. No much info out there for AS3.

function generate_lrc(string: String) {
    var lrc = 0
    var text = string.split('');
    for (var i: Number = 0; i < text.length; i++) {
        lrc ^= text[i].charCodeAt(0);
    }
    trace('lrc = ' + lrc);
    return lrc;
}

Any help will be appreciated, thank you!


Solution

  • I don't see the problem with the script (you don't have to split the String, but whatever). What you can do is to trace all ins and outs, like that:

    function generate_lrc(source:String):uint
    {
        var lrc:uint = 0;
        
        for (var i:int = 0; i < source.length; i++)
        {
            var aChar:String = source.charAt(i);
            var aByte:uint = source.charCodeAt(i);
            var newLrc:uint = lrc ^ aByte;
            
            trace(aChar + ":", lrc.toString(2), "XOR", aByte.toString(2), "=", newLrc.toString(2));
            
            lrc = newLrc;
        }
        
        return lrc;
    }