Go io reader包装器

huangapple go评论150阅读模式
英文:

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 (
    &quot;io&quot;
    &quot;os&quot;
    &quot;strings&quot;
)

type rot13Reader struct {
    r io.Reader
}

func cipher(in byte) (out byte) {
    out = in
    if in &gt; 64 &amp;&amp; in &lt; 91 {
        out = in - 64
        out = out + 13
        out = out % 26
        out = out + 64
    }
    if in &gt; 96 &amp;&amp; in &lt; 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(
        &quot;Lbh penpxrq gur pbqr!\n&quot;)
    r := rot13Reader{s}
    io.Copy(os.Stdout, &amp;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.

huangapple
  • 本文由 发表于 2013年11月20日 10:30:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/20086205.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定