UTF-8 GB2312 中文乱码解决方案汇总

来源:

http://hi.baidu.com/zhenyk/blog/item/f5158f5108d3cc898d543067.html

string utfinfo = "document.write(/"alert('aa你好么??');/");";
string gb2312info = string.Empty;

Encoding utf8 = Encoding.UTF8;
Encoding gb2312 = Encoding.GetEncoding("gb2312");

// Convert the string into a byte[].
byte[] unicodeBytes = utf8.GetBytes(utfinfo);
// Perform the conversion from one encoding to the other.
byte[] asciiBytes = Encoding.Convert(utf8, gb2312, unicodeBytes);

// Convert the new byte[] into a char[] and then into a string.
// This is a slightly different approach to converting to illustrate
// the use of GetCharCount/GetChars.
char[] asciiChars = new char[gb2312.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
gb2312.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
gb2312info = new string(asciiChars);

汉字转换为UTF-8

function chinese2unicode(Str)
dim i
dim Str_one
dim Str_unicode
for i=1 to len(Str)
Str_one=Mid(Str,i,1)
Str_unicode=Str_unicode&chr(38)
Str_unicode=Str_unicode&chr(35)
Str_unicode=Str_unicode&chr(120)
Str_unicode=Str_unicode& Hex(ascw(Str_one))
Str_unicode=Str_unicode&chr(59)
next
Response.Write Str_unicode
end function

UTF-8 To GB2312

function UTF2GB(UTFStr)
for Dig=1 to len(UTFStr)
if mid(UTFStr,Dig,1)="%" then
if len(UTFStr) >= Dig+8 then
GBStr=GBStr & ConvChinese(mid(UTFStr,Dig,9))
Dig=Dig+8
else
GBStr=GBStr & mid(UTFStr,Dig,1)
end if
else
GBStr=GBStr & mid(UTFStr,Dig,1)
end if
next
UTF2GB=GBStr
end function

function ConvChinese(x)
A=split(mid(x,2),"%")
i=0
j=0
for i

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Java中,将UTF-8编码转换为GB2312编码可以使用Java的标准库中的一些类和方法来完成。 首先,我们需要将UTF-8编码的字符串转换为字节数组。可以使用Java内置的String类的getBytes方法,并传入UTF-8作为参数,如下所示: byte[] utf8Bytes = utf8String.getBytes("UTF-8"); 接下来,我们可以使用Java提供的Charset类来获取GB2312编码字符集对象。可以使用forName静态方法,传入"GB2312"作为参数,如下所示: Charset gb2312Charset = Charset.forName("GB2312"); 然后,我们可以使用CharsetEncoder类将UTF-8的字节数组编码为GB2312编码的字节数组。可以使用Charset对象的newEncoder方法来获取CharsetEncoder对象,然后使用encode方法进行编码,如下所示: CharsetEncoder gb2312Encoder = gb2312Charset.newEncoder(); ByteBuffer gb2312Buffer = gb2312Encoder.encode(ByteBuffer.wrap(utf8Bytes)); 最后,我们可以将GB2312编码的字节数组转换为字符串。可以使用ByteBuffer类和CharsetDecoder类来完成这个转换。首先,使用Charset对象的newDecoder方法获取CharsetDecoder对象,然后使用decode方法进行解码,并将结果转换为字符串,如下所示: CharsetDecoder gb2312Decoder = gb2312Charset.newDecoder(); String gb2312String = gb2312Decoder.decode(gb2312Buffer).toString(); 最终,gb2312String字符串就是将UTF-8编码转换为GB2312编码后的结果。 需要注意的是,UTF-8GB2312是不同的字符编码方式,转换过程中可能会有一些字符无法转换或产生乱码的情况,特别是当UTF-8编码中包含了GB2312无法表示的字符时。因此,在进行编码转换时,我们应该注意处理这些特殊情况。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值