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
+12.9k Golang : Generate Code128 barcode
+8.3k Golang : How to join strings?
+15.6k Golang : Get sub string example
+9.5k Golang : Ordinal and Ordinalize a given number to the English ordinal numeral
+18.1k Golang : Write file with io.WriteString
+6.9k Golang : Example of custom handler for Gorilla's Path usage.
+17.8k Golang : Aligning strings to right, left and center with fill example
+5.7k Javascript : Get operating system and browser information
+5.6k Golang : Measure execution time for a function
+9k Golang : How to protect your source code from client, hosting company or hacker?
+5.2k Golang : Detect words using using consecutive letters in a given string