I have an algorithm problem I need to solve. But I do not really understand the question after spending a day to grasp it.
PROBLEM: For this task, you need to write a small program including a pair of functions that can
convert an integer into a special text encoding 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 of 3
Format the two bytes as a single 4-character hexadecimal string and return it. Sample values:
Unencoded (decimal) | Intermediate (decimal) | Intermediate (hex) | Encoded (hex)
0 | 8192 | 2000 | 4000
-8192 | 0 | 0000 | 0000
8191 | 16383 | 3fff | 7F7F
2048 | 10240 | 2800 | 5000
-4096 | 4096 | 1000 | 2000
The part '2.Pack that value into two bytes such that the most significant bit of each is cleared' is my obstacle now.
what should I do with this instruction? Thank you so much in advance.
I tried to convert the number to 16bit by the code below. But I don't know what should do next.
let rawInput = parseInt(document.getElementById("inputValue").value);
let interDec= Number.parseInt(rawInput) + 8192
let interHex = interDec.toString(16)
When you added 8192 to integer, you have value of kind (binary representation) 00HHHHHH HLLLLLLL
1) You have to preserve right ( L
) bits - just separate them with bitwise AND using bitmask 0x7f
((binary 00000000 01111111
))
2) Shift all value left, getting 0HHHHHHH LLLLLLL0
, now H
bits stay at the final places
3) Separate H
bits with bitwise AND using mask 0x7f00
(binary 01111111 00000000
)
4) Combine low and high parts together with binary OR
Python example
v = 0x3fff
ev = (v & 0x7f) | ((v<<1) & 0x7f00)
print(hex(ev))
>>>0x7f7f
Try - the +('0b'+binString)
parse binary string to js number (the toString
, slice
and padStart
are standard well documented js functions)
function convert(num) { let b = (num+8192).toString(2).padStart(14,'0'); let L = ( +('0b'+b.slice(7)) ).toString(16).padStart(2,'0'); let H = ( +('0b'+b.slice(0,7)) ).toString(16).padStart(2,'0'); return H+L; } console.log(' 0 =>', convert( 0)); console.log('-8192 =>', convert(-8192)); console.log(' 8191 =>', convert( 8191)); console.log(' 2048 =>', convert( 2048)); console.log('-4096 =>', convert(-4096));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.