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
+5.4k PHP : Convert string to timestamp or datestamp before storing to database(MariaDB/MySQL)
+4.3k Java : Generate multiplication table example
+6.3k Golang : Calculate diameter, circumference, area, sphere surface and volume
+5.6k Linux : Disable and enable IPv4 forwarding
+52.2k Golang : How to get struct field and value by name
+8.2k Golang : Generate Datamatrix barcode
+8.9k Golang : Gonum standard normal random numbers example
+7.1k Golang : Accessing dataframe-go element by row, column and name example
+16.2k Golang : Convert slice to array
+5.4k Golang : Detect words using using consecutive letters in a given string
+4.7k JQuery : Calling a function inside Jquery(document) block
+12.1k Golang : Flush and close file created by os.Create and bufio.NewWriter example