Javascript String byteLength()
String.prototype.byteLength = function(){ var count = 0;//from www .ja va2 s . com for(var i=0;i<this.length;i++) if(this.charCodeAt(i) >= 00000000 && this.charCodeAt(i) <= 0x0000007F) count++ else if(this.charCodeAt(i) >= 0x00000080 && this.charCodeAt(i) <= 0x000007FF) count += 2 else if(this.charCodeAt(i) >= 0x00000800 && this.charCodeAt(i) <= 0x0000FFFF) count += 3 else if(this.charCodeAt(i) >= 0x00010000 && this.charCodeAt(i) <= 0x001FFFFF) count += 4 return count }
String.prototype.byteLength = function() { /**/*from w w w. j ava 2 s .co m*/ * JavaScript only includes the natural logarithm method, but it does have some useful constants * for certain values, so here is how we calculate log256 x: * log256 x = log2 x / log2 256 <=> log256 x = log2 x / 8 (8 will now be known as LOG2_256) * log2 x = logE x / logE 2 (JavaScript has a constant value for logE 2 => Math.LN2) * * log256 x = (logE x / Math.LN2) / LOG2_256 <=> log256 x = logE x / (LOG2_256 * Math.LN2) * * The final part of the calculation requires us to round up regardless of how small the * decimal portion, this means that if the value is not exactly whole, it has one more byte of information. */ var total = 0; var LOG2_256 = 8; var LN2x8 = Math.LN2 * LOG2_256; for(var i = 0; i < this.length; i++) total += Math.ceil(Math.log(this[i].charCodeAt()) / LN2x8); return total; };