KV memory and quantization · Medium

Signed INT4 Packing

Problem 38 of 50 · Python and NumPy

Problem

Pack signed four-bit integers into unsigned bytes. Store the first value in a byte’s low nibble and the second in its high nibble, using four-bit two’s-complement representation. If there is an odd last value, pad only the unused high nibble with zero. Return a list of byte integers; empty input returns [].

def pack_int4(values):

Constraints

  • values contains 0..64 integers in [-8,7].
  • Each output byte is in [0,255]; preserve the input value order.
  • Inputs satisfy these constraints; invalid-input handling is not graded. Use only Python standard library and NumPy.

Examples

Example 1

Arguments: [
  [
    1,
    2
  ]
]
Expected result: [
  33
]

Low nibble 1 plus high nibble 2×16 gives byte 33.

Example 2

Arguments: [
  [
    -1,
    -8
  ]
]
Expected result: [
  143
]

-1 is nibble 15 and -8 is nibble 8, giving 15+128=143.

Sign in to solve this problem

Browse all coding problems · Learn the foundations