Skip to content

Instantly share code, notes, and snippets.

@Fishrock123
Last active August 29, 2015 14:02
Show Gist options
  • Save Fishrock123/a3c5393f19dbd76b9141 to your computer and use it in GitHub Desktop.
Save Fishrock123/a3c5393f19dbd76b9141 to your computer and use it in GitHub Desktop.
Counts the average byte length in a unicode string. (lol)
// 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