Mike D - 1 year ago 101
C# Question

# Encoding / Decoding 14-bit from Int to Hex and vice versa

So I have this problem to solve:

Write a small program including a pair of functions that can

1. convert an integer into a special text encoding and then

2. convert the encoded value back into the original integer.

The Encoding Function

This function needs to accept a signed integer in the 14-bit range [-8192..+8191] and return a 4 character string.

The encoding process is as follows:

1. Add 8192 to the raw value, so its range is translated to [0..16383]

2. Pack that value into two bytes such that the most significant bit of each is cleared

Unencoded intermediate value (as a 16-bit integer):

``````00HHHHHH HLLLLLLL
``````

Encoded value:

``````0HHHHHHH 0LLLLLLL
``````

1. Format the two bytes as a single 4-character hexadecimal string and return it.

Sample values:

``````Unencoded (decimal)  Encoded (hex)

0                    4000

-8192                0000

8191                 7F7F

2048                 5000

-4096                2000
``````

The Decoding Function

Your decoding function should accept two bytes on input, both in the range [0x00..0x7F] and recombine them to return the corresponding integer between [-8192..+8191]

This is my encoding function that works, it produces the correct results.

``````    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;
}
``````

I need help with my decoding function, it's currently not producing the correct results, the decoding function takes two hex strings each in the range of 0x00 and 0x7F, combines them and returns the decoded integer.
In My decoding function I'm trying to reverse what I've done in my encoding function.

``````    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;
}
``````

When decoding, you are trying the shift the byte-value (00-7F) right. This would produce a lesser value (00-3F). Instead you should shift it left 7 bits, to produce a higher value (0000-3F80). This value can then be combined with the low bits to produce the desired value.

``````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;
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download