C#:1:string类型——>Ushort[] 2:Ushort[]——>string类型 经过1、2操作,string类型的内容不能变
答案:4 悬赏:0 手机版
解决时间 2021-03-15 23:10
- 提问者网友:棒棒糖
- 2021-03-15 05:46
详细:
最佳答案
- 五星知识达人网友:拜訪者
- 2021-03-15 06:19
楼主你好~
解释~
1:
string a = "asfasfa";
ushort[] b = new ushort[a.Length];
Array.Copy(a.ToCharArray(), b, a.Length);
2:
string c;
char[] d = new char[b.Length];
Array.Copy(b, d, b.Length);
c = new string(d);
Ushort存在到char型的隐式转换,所以直接用Array.Copy可以将a生成的char[]数组直接赋值到ushort[]数组。
反过来的操作也相同,直接使用Array.Copy将ushort数组直接赋值到char[]数组,然后用String的构造器直接生成string
解释~
1:
string a = "asfasfa";
ushort[] b = new ushort[a.Length];
Array.Copy(a.ToCharArray(), b, a.Length);
2:
string c;
char[] d = new char[b.Length];
Array.Copy(b, d, b.Length);
c = new string(d);
Ushort存在到char型的隐式转换,所以直接用Array.Copy可以将a生成的char[]数组直接赋值到ushort[]数组。
反过来的操作也相同,直接使用Array.Copy将ushort数组直接赋值到char[]数组,然后用String的构造器直接生成string
全部回答
- 1楼网友:渡鹤影
- 2021-03-15 08:59
可以,string转成byte数组然后再转成Ushort就没事了。。。
转回来也是一样。。。
- 2楼网友:怙棘
- 2021-03-15 07:54
ushort y = 65;
ushort v = 1;
y和v都是无符号整数, 其相加的结果是整形而非无符号整形,
因为 两个无符号整形的数相加如果返回值还是无符号整形有可能出现越界的问题。所以y+v 的返回值是整形的,
上面代码还可以改成 int z = y+v
- 3楼网友:几近狂妄
- 2021-03-15 06:33
鉴于题目说的是Ushort,那么假设你是按Unicode 16位来Encode:
static void Main(string[] args)
{
string a = "hello world";
ushort[] array = StringToUtfArray(a);
for (int i = 0; i < array.Length; ++i)
{
Console.Write(array[i].ToString("X4") + " ");
}
Console.WriteLine();
string ret = UtfArrayToString(array);
Console.WriteLine(ret);
Console.ReadKey();
}
static ushort[] StringToUtfArray(string input)
{
byte[] code = System.Text.Encoding.Unicode.GetBytes(input);
ushort[] output = new ushort[code.Length / 2];
for (int i = 0; i < output.Length; ++i)
{
output[i] = (ushort)(code[i * 2] | code[i * 2 + 1] << 8);
}
return output;
}
static string UtfArrayToString(ushort[] input)
{
byte[] code = new byte[input.Length * 2];
int idx = 0;
for (int i = 0; i < input.Length; i++)
{
code[idx++] = (byte)input[i];
code[idx++] = (byte)(input[i] >> 8);
}
return System.Text.Encoding.Unicode.GetString(code);
}
看了其他几位的回答,我想补充一下
首先,题目说Ushort,很明显是16bits的类型,String要转换成16Bits,那么很可能是Unicode Encoding,也就是WChar。这里我们用System.Text.Encoding.Unicode来对String转换。
拿回来的Byte Array要转换成UShort,那么要将他2个Byte一组,组合成Hi Byte和Lo Byte,由于Unicode是反过来的(little endian),所以我们把每偶数个的Byte Shift上高位,然后和奇数位的数拼起来。
反向的操作是一样的。
以上的Code经过Compile和测试没问题。
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯