C# 从Int到Hex的14位编码/解码,反之亦然
所以我有一个问题要解决: 编写一个小程序,包括一对函数,可以C# 从Int到Hex的14位编码/解码,反之亦然,c#,.net,encoding,decoding,C#,.net,Encoding,Decoding,所以我有一个问题要解决: 编写一个小程序,包括一对函数,可以 将整数转换为特殊的文本编码,然后 将编码值转换回原始整数 编码功能 此函数需要接受14位范围[-8192..+8191]内的有符号整数,并返回4个字符的字符串 编码过程如下: 将8192添加到原始值,使其范围转换为[0..16383] 将该值打包为两个字节,以便清除每个字节的最高有效位 未编码中间值(作为16位整数): 编码值: 0HHHHHHH 0LLLLLLL 将两个字节格式化为一个4字符的十六进制字符串并返回 样本值: Une
0HHHHHHH 0LLLLLLL
Unencoded (decimal) Encoded (hex)
0 4000
-8192 0000
8191 7F7F
2048 5000
-4096 2000
解码功能
解码函数应在输入时接受两个字节,都在[0x00..0x7F]范围内,并重新组合它们以返回[-8192..+8191]之间的相应整数
这是我的编码功能,它可以产生正确的结果
public static string encode(int num)
{
string result = "";
int translated = num + 8192;
int lowSevenBits = translated & 0x007F; // 0000 0000 0111 1111
int highSevenBits = translated & 0x3F80; // 0011 1111 1000 0000
int composed = lowSevenBits + (highSevenBits << 1);
result = composed.ToString("X");
return result;
}
解码时,尝试将字节值(00-7F)向右移位。这将产生较小的值(00-3F)。相反,您应该将其左移7位,以产生更高的值(0000-3F80)。然后可将该值与低位组合以产生所需值
public static short decode(string loByte, string hiByte)
{
byte lo = Convert.ToByte(loByte, 16);
byte hi = Convert.ToByte(hiByte, 16);
short composed = (short)(lo + (hi << 7));
short result = (short)(composed - 8192);
return result;
}
公共静态短解码(字符串loByte,字符串hiByte)
{
字节lo=Convert.ToByte(loByte,16);
字节hi=转换为字节(hiByte,16);
short Composited=(short)(lo+)(您好,您已经说过您需要有关解码功能的帮助,但是您已经进入了许多不相关的细节,而没有实际描述它的错误。@Adrianwrag谢谢,我更新了我的问题谢谢,这很有意义。
public static short decode(string loByte, string hiByte)
{
byte lo = Convert.ToByte(loByte, 16);
byte hi = Convert.ToByte(hiByte, 16);
short composed = (short)(lo + (hi >> 1));
short result = (short)(composed - 8192);
return result;
}
public static short decode(string loByte, string hiByte)
{
byte lo = Convert.ToByte(loByte, 16);
byte hi = Convert.ToByte(hiByte, 16);
short composed = (short)(lo + (hi << 7));
short result = (short)(composed - 8192);
return result;
}