【发布时间】:2016-10-24 06:20:58
【问题描述】:
所以我有这个问题要解决:
编写一个包含一对函数的小程序
将整数转换为特殊的文本编码,然后
将编码值转换回原始整数。
编码函数
这个函数需要接受一个14位范围[-8192..+8191]的有符号整数,并返回一个4个字符的字符串。
编码过程如下:
将 8192 添加到原始值,因此其范围转换为 [0..16383]
将该值打包成两个字节,以便清除每个字节的最高有效位
未编码的中间值(作为 16 位整数):
00HHHHHH HLLLLLLL
编码值:
0HHHHHHH 0LLLLLLL
- 将这两个字节格式化为单个 4 字符的十六进制字符串并返回。
示例值:
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;
}
我的 解码 函数需要帮助,它目前没有产生正确的结果,解码函数需要两个十六进制字符串,每个字符串都在 0x00 和 0x7F 的范围内,将它们组合并返回解码后的整数。 在我的解码功能中,我试图扭转我在编码功能中所做的事情。
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;
}
【问题讨论】:
-
您已经声明您需要解码功能方面的帮助,但是您已经进入了很多不相关的细节,并没有真正描述它有什么问题。 stackoverflow.com/help/mcve
-
@AdrianWragg 谢谢,我更新了我的问题