Converting ISO Country Codes to Flag Emojis

3 min read Original article ↗

Today I learned something that is probably already well-known in some circles… but I hadn’t noticed it before and it made me go “wow”:

There’s a really simple algorithm for converting ISO 3166-1 alpha-2 country codes into the emoji representations of the flags of those countries.

I made an interactive to show how it works (enter a two-letter country code!). There’s a longer explanation below:

Non-interactive widget demonstrative conversion of two-letter ISO country codes into emoji flags.

Here’s the essence of the algorithm:

  1. Take the two-letter country code, e.g. FR for France.
  2. Get the character code of the uppercase variant of each letter: so F becomes 70 and R becomes 82.1
  3. Add 127,397 to each of them, so now F is 127,467 and R 127,479.
  4. Render the unicode characters at those codepoints: F turns into 🇫 and R turns into 🇷.
  5. Concatenate those characters and you get the emoji of the flag: 🇫🇷

I’ve often find things that are wonderfully clever about Unicode, but this might be my new favourite.

func countryEmojiFlag(countryCode string) string {
  cc := strings.ToUpper(strings.TrimSpace(countryCode))
  if len(cc) != 2 || cc[0] < 'A' || cc[0] > 'Z' || cc[1] < 'A' || cc[1] > 'Z' {
    return ""
  }
  return string([]rune{rune(cc[0]) + 127397, rune(cc[1]) + 127397})
}
My actual implementation was Go, rather than JavaScript2, as part of a side project this weekend. Here’s the function I came up with.

Today was also the day that I discovered that while SU is a reserved 2-letter ISO 3166-1 designation for the Soviet Union, the flag of the USSR is not a registered emoji. But if it were, we can work out what codepoint it’d be at! So I can type this – 🇸🇺 – here, safe in the knowledge that if that emoji comes to exist in the future, then you’ll be able to revisit this blog post and see it!


You know what: there might be a game in these country codes and their flags somewhere. Like: a game where you have to get from one country to another: like, say, from the 🇨🇰 Cook Islands (CK) to 🇧🇯 Benin (BJ). But you’re only allowed to change one letter at a time and you have to land in a real country. I think the fastest route between those two takes three steps, e.g. 🇨🇰 Cook Islands (CK) to 🇹🇰 Tokelau (TK) to 🇹🇯 Tajikstan (TJ) to 🇧🇯 Benin (BJ)… It’s probably a bit easy though: I haven’t yet found any that require more than three moves and most can be done in just two.

It gets a lot harder if you require letters to only be changed to an adjacent letter, but this variant makes some permutations impossible. Maybe there’s an optimisation puzzle in the style of the Travelling Salesman problem? Or maybe by mixing in geographical restrictions such as an inability to visit a certain continent that would make it more challenging and fun? Just brainstorming here…