Keep Only the Highest Set Bit

Code

#include <stdio.h>
#include <stdint.h>
#include <math.h>

void printBinary(uint16_t x);  //custom function to print binary eq.

uint16_t highest_set_bit(uint16_t reg) {
    //OVERVIEW
    //Create a mask that will start from MSB(left) and sequentially move -> (right)
    //Mask will compare against register data & check for a set bit
    //Once set bit has been found...
    //1. (SET MASK STARTING POSITION MSB FIRST - LEFT (16bit number))
    uint16_t mask = (1U << 15); //(1000 0000 0000 0000)
    int firstSetBitPosition;
    //2. ITTERATE THROUGH DATA BYTES(reg) & CHECK FOR FIRST SET BIT (mask & reg)
    for(int i =0;i<16;i++){
        //If reg&mask have any value (not 0) then we have a set bit
        //the set bit will be a 1 but != 1 as 1000 = 8 not 1
        if(reg & mask){ 
        firstSetBitPosition = 16-i-1; //Finds position of first bit
        return pow(2,firstSetBitPosition); //Keeps only the highest bit
        
        //SOLUTION 2:
        //Mask already is the answer as it only has the 1 bit and finds the
        //highest bit once it reaches this point
        //return mask;
        } 
        mask >>= 1; //move mask 1 place to right
    }
    return 0;
}

int main() {
    uint16_t reg;
    scanf("%hu", &reg);

    uint16_t result = highest_set_bit(reg);
    printf("%hu", result);
    return 0;
}

void printBinary(uint16_t x){
    //1. Find size of passed int
    int num_bits = sizeof(x)*8;
    //2. loop through every bit and perform checkbit
    //printf("Int value is: %hhu, Num of bits is: %d\n",x, num_bits);
    for(int i=num_bits-1;i>=0;i--){
    //Prints a space every 4 bits
    if ((i+1)%4==0 && i+1 != sizeof(x)*8){
        printf(" ");
    }
    if (x & (1 << i)){
        printf("1");
    } 
    else{
        printf("0");
    }
    }
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

44

Expected Output

32