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
+6.9k Restart Apache or Nginx web server without password prompt
+17.9k Golang : Check if a directory exist or not
+4.9k Linux : How to set root password in Linux Mint
+11.9k Golang : Detect user location with HTML5 geo-location
+9.9k Golang : Get login name from environment and prompt for password
+7.3k Golang : Process json data with Jason package
+7.7k Golang : Scan files for certain pattern and rename part of the files
+13.3k Golang : Read XML elements data with xml.CharData example
+6.4k PHP : Shuffle to display different content or advertisement
+13.8k Golang : convert rune to unicode hexadecimal value and back to rune character
+14.4k Golang : Convert(cast) int to float example