FastPrepExtract a Register Bit Field

Extract a Register Bit Field

Apple logoApple● EasyNEW GRADONSITE INTERVIEW
Learn

Problem statement

An unsigned 32-bit register contains the integer value. Bit positions are numbered from zero at the least significant bit.

Extract the width consecutive bits beginning at offset, shift that field down so its lowest bit becomes bit zero, and return its unsigned numeric value. Do not change the register value.

Function

extractRegisterBits(value: long, offset: int, width: int) → long

Examples

Example 1

value = 42offset = 1width = 3return = 5

Binary 101010 shifted right once has low three bits 101, whose value is five.

Example 2

value = 4294967295offset = 0width = 32return = 4294967295

Selecting the full register preserves all thirty-two one bits.

Constraints

  • 0 <= value <= 4294967295.
  • 0 <= offset <= 31.
  • 1 <= width <= 32 and offset + width <= 32.
  • The interface uses a signed 64-bit type to represent the full unsigned 32-bit range.

More Apple problems

See Apple hiring insights
public long extractRegisterBits(long value, int offset, int width) {
    // Write your solution here.
}
value42
offset1
width3
expected5
Checking account…