AS3:可以的ByteArray返回其内容为一个字符串,每UNI code字两个字节?字符串、字节、两个、内容

2023-09-08 13:57:33 作者:Guetse(乱情)

var bytes:ByteArray = new ByteArray;
bytes.writeInt(0);

trace(bytes.length); // prints 4
trace(bytes.toString().length); // prints 4

当我运行上面的code的输出显示,每一个字符用的toString返回的字符串中包含从ByteArray中的一个字节。当然,这是伟大的,如果你想显示的ByteArray的内容,但不是那么大,如果你想发送的内容连接codeD在一个字符串,字符串事项的大小。

When I run the above code the output suggests that every character in the string returned by toString contains one byte from the ByteArray. This is of course great if you want to display the content of the ByteArray, but not so great if you want to send its content encoded in a string and the size of the string matters.

是否有可能从那里每个字符的字符串中包含从ByteArray的?

Is it possible to get a string from the ByteArray where every character in the string contains two bytes from the ByteArray?

推荐答案

您可以reinter preT你的的ByteArray 为只含短裤。这可以让你读两个字节的时间和重新获得$ P $单一数值psenting他们两个。接下来,你可以把这些数字和reinter preT它们作为字符codeS。最后,创建一个字符串从这些字符codeS,你就大功告成了。

You can reinterpret your ByteArray as containing only shorts. This lets you read two bytes at a time and get a single number value representing them both. Next, you can take these numbers and reinterpret them as being character codes. Finally, create a String from these character codes and you're done.

public static function encode(ba:ByteArray):String {
    var origPos:uint = ba.position;
    var result:Array = new Array();

    for (ba.position = 0; ba.position < ba.length - 1; )
        result.push(ba.readShort());

    if (ba.position != ba.length)
        result.push(ba.readByte() << 8);

    ba.position = origPos;
    return String.fromCharCode.apply(null, result);
}

还有一个特殊情况要注意。如果您尝试读取short从的ByteArray 时,只有一个留在它字节,一个异常将被抛出。在这种情况下,你应该叫 readByte 与价值转移8位来代替。这是一样的,如果原始的ByteArray 有一个额外的0字节的末端。 (使它甚至在长度)

There is one special circumstance to pay attention to. If you try reading a short from a ByteArray when there is only one byte remaining in it, an exception will be thrown. In this case, you should call readByte with the value shifted 8 bits instead. This is the same as if the original ByteArray had an extra 0 byte at the end. (making it even in length)

现在,作为该字符串解码...获取每个字符的字符code,并将它们放置到一个新的的ByteArray 短裤。这将是等同于原始的,除了如果原始有奇数字节的,在这种情况下,日$ C $光盘的ByteArray 将有额外的0字节的结束。

Now, as for decoding this String... Get the character code of each character, and place them into a new ByteArray as shorts. It will be identical to the original, except if the original had an odd number of bytes, in which case the decoded ByteArray will have an extra 0 byte at the end.

public static function decode(str:String):ByteArray {
    var result:ByteArray = new ByteArray();
    for (var i:int = 0; i < str.length; ++i) {
        result.writeShort(str.charCodeAt(i));
    }
    result.position = 0;
    return result;
}

在行动:

var ba:ByteArray = new ByteArray();

ba.writeInt(47);
ba.writeUTF("Goodbye, cruel world!");

var str:String = encode(ba);
ba = decode(str);

trace(ba.readInt());
trace(ba.readUTF());