各位朋友,下面这个utf16to8的js方法,怎样将结果转为gb2312啊?
这是用js生成二维码的一个中文支持的方法。(http://www.cnblogs.com/pfbk/p/4848875.html就是这个),但现在只有国标的设备,只支持gb2312,所以要将utf8换成国标gb2312。
function utf16to8(str) {
var out, i, len, c;
out = "";
len = str.length;
for (i = 0; i < len; i++) {
c = str.charCodeAt(i);
if ((c >= 0x0001) && (c <= 0x007F)) {
out += str.charAt(i);
} else if (c > 0x07FF) {
out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
} else {
out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
}
}
return out;
}
//把编码转换成 gb2312编码
function UrlEncode(str)
{
var i, c, ret="", strSpecial="!\"#$%&'()*+,/:;<=>?@[\]^`{|}~%";
for(i = 0; i < str.length; i++)
{
//alert(str.charCodeAt(i));
c = str.charAt(i);
if(c==" ")
ret+="+";
else if(strSpecial.indexOf(c)!=-1)
ret += "%" + str.charCodeAt(i).toString(16);
if(z[str.charCodeAt(i)] != null)
{
d = z[str.charCodeAt(i)];
try
{
ret += "%" + d.slice(0,2) + "%" + d.slice(-2);
}
catch (e)
{
alert(" $$ error name = " + e.name + ", message = " +e.message + ", d " + i + "= " + str.charCodeAt(i))
}
} //(jquery中文网 www.jquerycn.cn)
else
ret += c;
}
return ret;
}
function getSpell(str, sp)
{
var i, c, t, ret="";
if(sp == null)
sp="";
for(i = 0; i < str.length; i++)
{
if(str.charCodeAt(i) >= 0x4e00)
{
c = parseInt(z[str.charCodeAt(i)], 16);
if(c < 55290)
{
for(t = qswhSpell.length-1; t > 0; t = t - 2)
if(qswhSpell[t] <= c)
break;
if(t > 0)
ret += qswhSpell[t - 1] + sp;
}
}
} a
return ret.substr(0, ret.length-sp.length);
}
/// <summary>
/// GB2312转换成UTF8
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string gb2312_utf8(string text)
{
//声明字符集
System.Text.Encoding utf8, gb2312;
//gb2312
gb2312 = System.Text.Encoding.GetEncoding("gb2312");
//utf8
utf8 = System.Text.Encoding.GetEncoding("utf-8");
byte[] gb;
gb = gb2312.GetBytes(text);
gb = System.Text.Encoding.Convert(gb2312, utf8, gb);
//返回转换后的字符
return utf8.GetString(gb);
}
/// <summary>
/// UTF8转换成GB2312
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string utf8_gb2312(string text)
{
//声明字符集
System.Text.Encoding utf8, gb2312;
//utf8
utf8 = System.Text.Encoding.GetEncoding("utf-8");
//gb2312
gb2312 = System.Text.Encoding.GetEncoding("gb2312");
byte[] utf;
utf = utf8.GetBytes(text);
utf = System.Text.Encoding.Convert(utf8, gb2312, utf);
//返回转换后的字符
return gb2312.GetString(utf);
}
请各位朋友先仔细看看我的那段方法好吗?我就是要把最后return的out转成gb2312的。。