PPractick

DSA interview question

Binary Representation and Bit Basics (Two's Complement)

Easy · Algorithms · Topics: bit manipulation

The problem

A network tool displays packet header fields as raw bits and lets engineers type bit patterns back in. You need two helpers: toBinary(n) shows the exact 32 bits a signed int is stored as, and fromBinary(s) turns a bit string (most significant bit first) back into the int. Negative numbers are the interesting part. Computers store them in two's complement, so −1 is all ones and INT_MIN is a lone sign bit. Writing these helpers exercises the basic toolkit behind every bit-manipulation problem: shifts, masks, and the difference between signed and unsigned views of the same bits.

Example: toBinary(13) → 0000 0000 0000 0000 0000 0000 0000 1101; fromBinary("1101") → 13.

Function signature

string toBinary(int n);            // exactly 32 characters, most significant bit first
int fromBinary(const string& s);   // 1 to 32 bits, most significant first; 32 bits may encode a negative

Test cases

InputOutputExplanation
toBinary(13)0000 0000 0000 0000 0000 0000 0000 11018 + 4 + 1 (spaces added for readability)
toBinary(-1)1111 1111 1111 1111 1111 1111 1111 1111Two's complement of −1 is all ones
toBinary(0)0000 0000 0000 0000 0000 0000 0000 0000
toBinary(INT_MIN)1000 0000 0000 0000 0000 0000 0000 0000Only the sign bit
fromBinary("1101")13
fromBinary of 32 ones-1

(Confirm: ints are 32-bit two's complement; toBinary always returns 32 characters; fromBinary reads its input most significant bit first.)

How interviewers phrase it

Clarifying questions to ask

  1. Fixed 32 bits, or the minimal representation without leading zeros?
  2. How should negatives be shown: two's complement or a minus sign?
  3. Which end comes first in the string? (Most significant bit first.)

Follow-ups to expect

  1. "What is two's complement?"
  2. "Why cast to unsigned before shifting?"
  3. "List the core tricks."
  4. "How many bits does a number need?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in