moock.org is supported in part by


April 05, 2009

get number of bytes in a UTF-8 string

Here's a handy little ActionScript function that reports the number of bytes in a UTF-8 encoded string (the default encoding for ActionScript):

public function getNumBytesUTF8 (s:String):Number {
  var byteArray:ByteArray = new ByteArray();
  byteArray.writeUTFBytes(s);
  return byteArray.length;
}
// Usage:
trace(getNumBytesUTF8("automobile"));  // 10
trace(getNumBytesUTF8("車"));          // 3

Note: "number of bytes" is not the same thing as "number of characters". For "number of characters," use the String class's length variable:

trace("車".length); // 1
Posted by moock at April 5, 2009 08:39 PM