Golang : ROT32768 (rotate by 0x80) UTF-8 strings example
Previously we learned how to implement ROT13, ROT5 and ROT47 character substitution algorithms in Golang. However, these implementations are meant for rotating ASCII characters. If you try to rotate UTF-8 strings, you will be disappointed because ASCII != UTF8
.
The following is the implementation of ROT32768 (rotate by 0x80) that will be able to handle UTF-8 strings with added ROT5 mapping to handle ASCII digits rotation. It will be handle ASCII characters as well and in fact, it would be a better choice to use ROT32768 than ROT13 or ROT47 because the resulting rotation is hard to distinguish by human eyes.
For example: handle alphabets
to èáîäìå áìðèáâåôó
Here you go!
package main
import (
"fmt"
"strings"
"unicode"
"unicode/utf8"
)
// rot32768 rotates utf8 string
// rot5map rotates digits
func rot32768(input string) string {
var result []string
rot5map := map[rune]rune{'0': '5', '1': '6', '2': '7', '3': '8', '4': '9', '5': '0', '6': '1', '7': '2', '8': '3', '9': '4'}
for _,i := range input {
switch {
case unicode.IsSpace(i):
result = append(result, " ")
case i >= '0' && i <= '9':
result = append(result, string(rot5map[i]))
case utf8.ValidRune(i):
//result = append(result, string(rune(i) ^ 0x80))
result = append(result, string(rune(i) ^ utf8.RuneSelf))
}
}
return strings.Join(result,"")
}
func main() {
text := "жѳМѭњЂЯёЧВ 一二三 handle alphabets = ขอพฮศโำฐเฦ abc世界你好123 ペツワケザユプルヂザ"
fmt.Println(text)
fmt.Println(rot32768(text))
fmt.Println("Invertible test:")
fmt.Println(rot32768(rot32768(text)))
}
Output:
жѳМѭњЂЯёЧВ 一二三 handle alphabets = ขอพฮศโำฐเฦ abc世界你好123 ペツワケザユプルヂザ
ҶӳҜӭӚ҂үӑҧҒ 亀丌争 èáîäìå áìðèáâåôó ½ ຂອພຮຨໂຳຐເ áâã亖痌俠姽678 ずいは〱〶てしにあ〶
Invertible test:
жѳМѭњЂЯёЧВ 一二三 handle alphabets = ขอพฮศโำฐเฦ abc世界你好123 ペツワケザユプルヂザ
Happy coding!
See also : Golang : Rot13 and Rot5 algorithms example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+9k Golang : Temperatures conversion example
+5.8k nginx : force all pages to be SSL
+27k Golang : Convert CSV data to JSON format and save to file
+10.3k Golang : Get local time and equivalent time in different time zone
+19.4k Golang : Set or Add HTTP Request Headers
+8.7k Golang : Get SPF and DMARC from email headers to fight spam
+22.9k Golang : Print out struct values in string format
+4.2k Golang : Valued expressions and functions example
+6.7k Golang : Pat multiplexer routing example
+11.5k Golang : GTK Input dialog box examples
+14.6k Golang : Basic authentication with .htpasswd file
+8.5k Golang : Find duplicate files with filepath.Walk