ISO-8859-1 到 UTF8 的转换

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

ISO-8859-1 to UTF8 conversion

问题

以下代码片段将ISO-8859-1编码的文本转换为UTF8。我不太明白这里发生了什么。有人可以解释一下为什么这样可以工作吗?

var utf8Buf bytes.Buffer
for _, b := range iso8859Slice {
  utf8Buf.WriteRune(rune(b))
}
utf8Str := utf8Buf.String()

这段代码的作用是将ISO-8859-1编码的文本转换为UTF8编码。代码中使用了一个bytes.Buffer类型的变量utf8Buf来存储转换后的UTF8文本。然后,通过遍历iso8859Slice中的每个字节,将其转换为rune类型,并使用utf8Buf.WriteRune方法将其写入utf8Buf中。最后,通过utf8Buf.String()方法将utf8Buf中的内容转换为字符串形式,存储在utf8Str变量中。

这段代码的原理是将ISO-8859-1编码的每个字节转换为对应的UTF8编码的rune类型,并将其逐个写入utf8Buf中,最终得到完整的UTF8编码的字符串。

英文:

The following snippet converts ISO-8859-1 encoded text to UTF8. I don't exactly understand what's going on here. Can someone explain why this works?

var utf8Buf bytes.Buffer
for _, b := range iso8859Slice {
  utf8Buf.WriteRune(rune(b))
}
utf8Str := utf8Buf.String()

答案1

得分: 1

循环遍历iso8859Str切片的每个字节,假设它的类型是[]byte

因为iso-8859-1被纳入Unicode的前256个代码点,所以你不需要实际将iso-8859-1转换为Unicode。

然而,你需要对Unicode符文进行UTF-8编码。可以通过Buffer.WriteRune()方法实现。

WriteRune方法将Unicode码点r的UTF-8编码附加到缓冲区中。

英文:

The loop takes each byte of the iso8859Str slice assuming it is of type []byte

Because iso-8859-1 is incorperated as the first 256 code points of Unicode, you have no need of actual conversion from iso-8859-1 to Unicode.

However, what you need to do is to UTF-8 encode the Unicode rune. This is done by Buffer.WriteRune()

> WriteRune appends the UTF-8 encoding of Unicode code point r to the buffer

答案2

得分: 1

首先,如果iso8859Str的类型是字符串,它不起作用

但是,如果iso8859Str的类型是[]byte,那么你的range语句将迭代字节,
这就是Unicode的设计方式:ISO 8859-1中的字节对应于相同的Unicode码点。

英文:

First: It does not work if iso8859Str is of type string!

But if iso8859Str is of type []byte your range clause iterates over bytes and
that is how unicode was designed: Bytes in ISO 8859-1 correspond to the same unicode codepoint.

huangapple
  • 本文由 发表于 2013年9月18日 19:21:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/18870883.html
匿名

发表评论

匿名网友

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

确定