Zhao Tian Programmer 博客

ruby字节转字符串

#ruby 字节转字符串 
"a我c".bytes.pack("c*").force_encoding("UTF-8")

#读文件16进制转utf8
open("XX.log").read.scan(/(..)./).map{|x| x[0].hex.chr}.join.force_encoding("gb2312").encode('utf-8','gb2312',{:invalid => :replace, :undef => :replace, :replace => '?'})

#字符串16进制转utf8
"1b 70 00 80 80 20 20 20 c6 b7 c3 fb 20 20 20 20 20 20 ca fd c1 bf 20 20 20 b5 a5 bc db 20 20 20 20 d0 a1 bc c6 0a 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 0a 31 20 20 cd de b9 fe b9 fe b4 bf be bb cb ae 35 39 36 6d 6c 20 20 20 20 20 20 20 20 20 20 20 0a 20 20 20 20 20 20 20 20 20 20 20 20 20 ".scan(/(..)./).map{|x| x[0].hex.chr}.join.force_encoding("gb2312").encode('utf-8','gb2312',{:invalid => :replace, :undef => :replace, :replace => '?'})

"\ep\u0000??   品名      数量   单价    小计\n--------------------------------\n1  娃哈哈纯净水596ml           \n             "

xx.log

1b 70 00 80 80 20 20 20 c6 b7 c3 fb 20 20 20 20 20 20 ca fd c1 bf 20 20 20 b5 a5 bc db 20 20 20 20 d0 a1 bc c6 0a 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 0a 31 20 20 cd de b9 fe b9 fe b4 bf be bb cb ae 35 39 36 6d 6c 20 20 20 20 20 20 20 20 20 20 20 0a 20 20 20 20 20 20 20 20 20 20 20 20 20 

评论

添加评论




预览