英文:
Go io reader wrapper
问题
我已经编写了以下代码,尝试使用13位密码对字母数字字符进行加密。这是Go之旅中的一个示例。
我使用日志库来检查字节数组p中的值,在加密后它们似乎被旋转了13位。由于某种原因,当它打印到STDOUT时,字符没有被加密。
我是否错误地修改了字节数组p?
package main
import (
"io"
"os"
"strings"
)
type rot13Reader struct {
r io.Reader
}
func cipher(in byte) (out byte) {
out = in
if in > 64 && in < 91 {
out = in - 64
out = out + 13
out = out % 26
out = out + 64
}
if in > 96 && in < 123 {
out = in - 96
out = out + 13
out = out % 26
out = out + 96
}
return
}
func (reader rot13Reader) Read(p []byte) (n int, err error) {
for index := range p {
p[index] = cipher(p[index])
}
n, err = reader.r.Read(p)
return
}
func main() {
s := strings.NewReader(
"Lbh penpxrq gur pbqr!\n")
r := rot13Reader{s}
io.Copy(os.Stdout, &r)
}
英文:
I have written the following code which tries to cipher the alpha numberic characters by 13. This is an example in the tour of go.
I have used the log library to check out the values in the byte array p, after the cipher, and they seem to be rotated by 13. For some reason when it prints to STDOUT, the characters are not ciphered.
I am altering byte array p incorrectly?
package main
import (
"io"
"os"
"strings"
)
type rot13Reader struct {
r io.Reader
}
func cipher(in byte) (out byte) {
out = in
if in > 64 && in < 91 {
out = in - 64
out = out + 13
out = out % 26
out = out + 64
}
if in > 96 && in < 123 {
out = in - 96
out = out + 13
out = out % 26
out = out + 96
}
return
}
func (reader rot13Reader) Read(p []byte) (n int, err error) {
for index := range p {
p[index] = cipher(p[index])
}
n, err = reader.r.Read(p)
return
}
func main() {
s := strings.NewReader(
"Lbh penpxrq gur pbqr!\n")
r := rot13Reader{s}
io.Copy(os.Stdout, &r)
}
答案1
得分: 1
在你的rot13Reader.Read
方法中,你首先将cipher
应用于p
中的任何数据,然后通过从子读取器中读取来覆盖该数据。
如果目的是解码你读取的内容,你应该按相反的顺序执行这两个操作。
英文:
In your rot13Reader.Read
method, you are first applying cipher
to whatever data was in p
and then overwriting that data by reading from the sub-Reader.
If the aim is to decode what you read, you should perform these two operations in the opposite order.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论