ActionScript ByteArray manipulation
I开发者_Go百科 have some binary data and I can't store it in a string, as such I'm using a ByteArray. The problem is that I need some functionality that comes with strings, to be specific I need the charAt, substr, indexOf and substring methods.
These would be fairly easy to implement. I can post the code if wanted. Is the data string-like? Or does it need to be treated as arbitrary binary? In either case, how wide are characters (e.g. 8-bit, 16-bit)?
public static function charAt(bytes:ByteArray, index:int):String {
if (bytes.length <= index) return null;
return String.fromCharCode(bytes[index]);
}
public static function substr(bytes:ByteArray, start:int, length:int=0):String {
var res:ByteArray = bytes.readBytes(bytes, start, length);
return res.toString();
}
public static function substring(bytes:ByteArray, start:int, end:int=0):String {
return substr(bytes, start, end-start);
}
public static function indexOf(bytes:ByteArray, str:String):int {
for (var i:int=0; i<bytes.length; i++) {
var strPos:int = 0;
while (String.fromCharCode(bytes[i+strPos]) == str.charAt(strPos)) {
strPos++;
if (strPos == str.length) return i;
}
}
return -1;
}
精彩评论