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
+4.6k Golang : A program that contain another program and executes it during run-time
+8.6k Golang : Sort lines of text example
+14.2k Golang : Overwrite previous output with count down timer
+14.6k Golang : Search folders for file recursively with wildcard support
+18.2k Golang : Write file with io.WriteString
+11k Use systeminfo to find out installed Windows Hotfix(s) or updates
+5.1k Unix/Linux/MacOSx : How to remove an environment variable ?
+5.4k Fix fatal error: evacuation not done in time problem
+9.4k Golang : Format strings to SEO friendly URL example
+9.1k Golang : Web(Javascript) to server-side websocket example
+10.2k Golang : Resolve domain name to IP4 and IP6 addresses.
+4.4k Javascript : Access JSON data example