Bit-Pack Telemetry Fields
A sensor sends readings over a low-bandwidth radio link, so fields are packed back to back with no byte alignment. Field i has value values[i] written in exactly widths[i] bits, most significant bit first. Fields follow one another in order, and the bit stream fills each byte starting from its most significant bit.
If the total number of bits is not a multiple of 8, pad the last byte with zero bits. Return the bytes as an array of numbers 0 to 255.
Example 1
Input: values = [5,3,1], widths = [3,2,3] Output: [185] Explanation: 101 + 11 + 001 = 10111001 = 185.
Example 2
Input: values = [1], widths = [1] Output: [128] Explanation: A single 1 bit then seven padding zeros.
Constraints
- 0 <= values.length == widths.length <= 10^4
- 1 <= widths[i] <= 32
- 0 <= values[i] < 2^widths[i]
Hint 1
A value with 32 bits does not fit in JS bitwise ints safely; use division by powers of two, or >>>.
Hint 2
Build a list of bits first, then group them into bytes.
Discussion 0
Join free to post in the discussion.
Good practice for: Embedded Systems Engineer, Game Developer, Blockchain Developer, Backend Developer, Mobile App Developer
Run checks your code on 3 sample tests. Submit runs all 9 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.