Skip to content

Instantly share code, notes, and snippets.

@fwon
Created June 13, 2017 09:38
Show Gist options
  • Save fwon/324a5d498700e01da003dfb123cfae3c to your computer and use it in GitHub Desktop.
Save fwon/324a5d498700e01da003dfb123cfae3c to your computer and use it in GitHub Desktop.
Get byte length
function getByteLen(normal_val) {
// Force string type
normal_val = String(normal_val);
var byteLen = 0;
for (var i = 0; i < normal_val.length; i++) {
var c = normal_val.charCodeAt(i);
byteLen += c < (1 << 7) ? 1 :
c < (1 << 11) ? 2 :
c < (1 << 16) ? 3 :
c < (1 << 21) ? 4 :
c < (1 << 26) ? 5 :
c < (1 << 31) ? 6 : Number.NaN;
}
return byteLen;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment