Last active
August 29, 2015 14:02
-
-
Save Fishrock123/a3c5393f19dbd76b9141 to your computer and use it in GitHub Desktop.
Counts the average byte length in a unicode string. (lol)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// assuming utf-8 where characters are "normally" 1 byte (so the byte's default length is 8 bits.) | |
import Cocoa | |
func lengthOfBytes(s: String) -> Double { | |
let count = Double(countElements(s)) | |
let bytes = Double(s.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) | |
let extra = (bytes - count) / count | |
return 8 * (1.0 + extra) | |
} | |
lengthOfBytes("Hello🐶x") // -> ~11.429 | |
lengthOfBytes("Hello✓x") // -> ~10.286 | |
lengthOfBytes("Hello©") // -> ~9.333 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment