`
fantaxy025025
  • 浏览: 1249612 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类

Ruby_byte_string_gbk_编码转换的问题

 
阅读更多

 

弄点儿细枝末节的问题,可能需要对知识更深入的理解。

 

需要把一个字节数组转换位GBK的字符串。

 

 

    bytes = file.read(18)
    puts bytes
    puts bytes.encoding
    puts "|#{bytes.encode("GBK")}|"

 这里报错:

 

 

Encoding::UndefinedConversionError: "\xC9" to UTF-8 in conversion from ASCII-8BIT to UTF-8 to GBK

    /mnt/ubuntu-64/unit/dxx_info_test.rb:68:in `encode'

    /mnt/ubuntu-64/unit/dxx_info_test.rb:68:in `block in <class:DxxInfoTest>'

 

 

上面语句 puts bytes.encoding 输出ASCII-8BIT

我并没有转化为utf-8

错误显示:先从ascii到utf8,之后再从utf8到gbk的时候报错了

 

    bytes = file.read(18)
    puts bytes
    puts bytes.encoding
    bytes.force_encoding("GBK")
    puts bytes.encode

 这样实现是可以的。

通过上面的对比,可以推测,这样写,在转换的时候,不会通过utf8的作为中转。

 

另外:

我把文件头的编码设置#encoding=utf-8去掉,或者换成#encoding=GBK 都是不行的。

这种设置,只能表示文件中的编码是utf8的,并不代表读入的流都是utf8的。

 

参考这里:

http://www.w3c.com.cn/ruby%E4%B8%AD%E6%9C%89%E6%B2%A1%E6%9C%89%E7%B1%BB%E5%BA%93%E8%83%BD%E5%9C%A8%E5%AD%97%E8%8A%82%E7%A0%81%E5%92%8C%E6%95%B0%E5%AD%97%E4%B9%8B%E9%97%B4%E8%BD%AC%E6%8D%A2%EF%BC%9F

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics