as3 ByteArray to Hex (binary hex representation)

2020-08-05 09:40发布

问题:

i hope someone can help me out here i have been struggling with this for a few days now.

i am receiving a UDP packet via AS3 UDP datagram socket in the format of a binary hex representation (which i believe to be RAW UDP data).

when i receive the UDP packet in as3 its in the ByteArray format which i need to convert back to the original Hexadecimal formatting.

this is how it should look:

EF BE AD DE
22 5C 88 06
5E 00 00 00
7C 11 FB 44
00 00 00 00
00 00 00 00
00 00 00 00
00 00 00 00
02 02 01 05
91 EE FE F4
04 00 00 00
00 00 01 00
11 00 00 00

this is my output in flash (it doesn't need the same spacing and line breaks just the same structure, from looking at it looks like its removing the zeros? i have no idea why its doing this):

hex= efbeaddea05b9515e0007d11fb440000000000000000221595ee76f54000001011000

here is my as3 function:

public function hex(data:ByteArray){
    var hex:String = "";
    data.position = 0;
    var len:uint = data.length;
    for (var i:uint = 0; i < len; ++i){
        var byte:uint = data.readUnsignedByte();
        hex += byte.toString(16).substr(-2);
    }
    trace("hex= "+hex);
}

any help would be greatly appreciated!!

回答1:

it looks like i have found a solution! as i did bit of digging and came across this function from the hurlant utilities class Hex.as this seems to be doing the trick! will report back after further investigation..

link to class: https://code.google.com/p/as3crypto/source/browse/trunk/as3crypto/src/com/hurlant/util/Hex.as?r=4

all i needed to change above was this, after importing the class:

trace("hex= "+Hex.fromArray(event.data);

here's the actual function:

public static function fromArray(array:ByteArray, colons:Boolean=false):String {
        var s:String = "";
        for (var i:uint=0;i<array.length;i++) {
                s+=("0"+array[i].toString(16)).substr(-2,2);
                if (colons) {
                        if (i<array.length-1) s+=":";
                }
        }
        return s;
}

original UDP packet (with all the padding removed):

EFBEADDE275A89005E000000FA1DFB440000000000000000000000000000000002020105891B0E3A040000000000010011000000

as3 received UDP packet after conversion from byteArray to Hexadecimal:

EFBEADDE655AF9025E000000FA1DFB4400000000000000000000000000000000020201058B1B4A3A040000000000010011000000

(these are not the exact same packets captured at the exact time, so they will look bit different).