Last active
July 10, 2019 11:52
-
-
Save nkcr/c0a448bb2e0867f5b9dc786c4b331f82 to your computer and use it in GitHub Desktop.
Hash to emoji in go
This file contains 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
var emap = getEmap() | |
// EmoHex returns the 8 bits emoji representation of a byte slice | |
func EmoHex(in []byte) string { | |
if os.Getenv("EMOJI") != "true" { | |
return fmt.Sprintf("%x", in) | |
} | |
res := "" | |
for _, el := range in { | |
res += html.UnescapeString("&#" + strconv.Itoa(emap[int(el)]) + ";") | |
} | |
return res | |
} | |
// EmoStr returns the 8 bits emoji representation of a string | |
func EmoStr(in string) string { | |
if os.Getenv("EMOJI") != "true" { | |
return in | |
} | |
data, err := hex.DecodeString(in) | |
if err != nil { | |
panic(err) | |
} | |
return EmoHex(data) | |
} | |
func getEmap() [256]int { | |
var emap [256]int | |
emoji := [][]int{ | |
{0x1F601, 0x1F64F}, | |
{0x1F680, 0x1F6C0}, | |
{0x1F600, 0x1F636}, | |
{0x1F681, 0x1F6C5}, | |
} | |
count := 0 | |
// Fill the emap, we need at least 256 emoji | |
for _, value := range emoji { | |
for x := value[0]; x < value[1]; x++ { | |
emap[count] = x | |
count++ | |
if count >= 256 { | |
break | |
} | |
} | |
} | |
return emap | |
} |
This file contains 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
/* | |
https://play.golang.org/p/rrLG3_id9m9 | |
*/ | |
package main | |
import ( | |
"fmt" | |
"html" | |
"strconv" | |
"crypto/sha256" | |
) | |
func main() { | |
// Ranges taken from: | |
// http://apps.timwhitlock.info/emoji/tables/unicode | |
var emap [256]int | |
emoji := [][]int{ | |
{0x1F601, 0x1F64F}, | |
{0x1F680, 0x1F6C0}, | |
{0x1F600, 0x1F636}, | |
{0x1F681, 0x1F6C5}, | |
} | |
count := 0 | |
// Fill the emap, we need at least 256 emoji | |
for _, value := range emoji { | |
for x := value[0]; x < value[1]; x++ { | |
emap[count] = x | |
count++ | |
if count >= 256 { | |
break | |
} | |
} | |
} | |
fmt.Printf("There is %d emojis\n", count) | |
h := sha256.New() | |
h.Write([]byte("ahello world\n")) | |
fmt.Printf("%x\n", h.Sum(nil)) | |
printHex(h.Sum(nil), emap) | |
} | |
func printHex(in []byte, emap [256]int) { | |
res := "" | |
for _, el := range in { | |
res += html.UnescapeString("&#" + strconv.Itoa(emap[int(el)]) + ";") | |
} | |
fmt.Printf("Res: %s\n", res) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment