欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

vb.net把汉字转换为GB2312编码,例如“广东”变成%B9%E3%B6%AB

程序员文章站 2023-12-06 14:09:10
gb2312是gbk编码的子集,使用gbk编码函数即可 'gbk编码(结果以百分号%进行分隔) public function gbkencode(byval sinput as string) a...
gb2312是gbk编码的子集,使用gbk编码函数即可
'gbk编码(结果以百分号%进行分隔)
public function gbkencode(byval sinput as string) as string
dim ret_gbkencode as string = ""
dim i as integer
dim startindex as integer = 0
dim endindex as integer
dim x() as byte = system.text.encoding.default.getbytes(sinput) '字符以及字符串在vb2008中都是以unicode编码存储的

endindex = x.length - 1
for i = startindex to endindex
ret_gbkencode &= "%" & hex(x(i))
next
return ret_gbkencode
end function

'gbk解码
public function gbkdevb.net把汉字转换为GB2312编码,例如“广东”变成%B9%E3%B6%ABcode(byval sinput as string) as string
sinput = sinput.replace("%", "")

dim ret_gbkdecode as string = ""
dim slen as integer = sinput.length
dim n as integer = slen \ 2
dim sbytes(0 to n - 1) as byte
'转化为字节码
for i as integer = 1 to n
sbytes(i - 1) = cbyte("&h" & sinput.substring(2 * i - 2, 2))
next
'将字节码转化为字符串
ret_gbkdecode = system.text.encoding.default.getstring(sbytes)
return ret_gbkdecode
end function