All submissions

Set Baud Rate Field in Control Register

Code

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

uint32_t set_baud_rate(uint32_t reg, uint8_t baud) {
    // Your code here
     int i,j=0,val=0;
     for(i=8;i<=11;i++){
        reg = reg & ~(1<<i);            // clearing the bits 
     }

    for(int k=0;k<4;k++){
      val = baud>>k&1;
       reg = reg | val << (8+k);        // left shifting the baud bits 
    }

    // reg = reg & ~(0xF << 8);        // clear the bits

    // reg = reg | ((baud)<<8);        // left shifting the baud bits

    return reg ;
}

int main() {
    uint32_t reg;
    uint8_t baud;
    scanf("%u %hhu", &reg, &baud);
    printf("%u", set_baud_rate(reg, baud));
    return 0;
}

Solving Approach

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

uint32_t set_baud_rate(uint32_t reg, uint8_t baud) {
    // Your code here
     int i,j=0,val=0;
     for(i=8;i<=11;i++){
        reg = reg & ~(1<<i);            // clearing the bits 
     }

    for(int k=0;k<4;k++){
      val = baud>>k&1;
       reg = reg | val << (8+k);        // left shifting the baud bits 
    }

    // reg = reg & ~(0xF << 8);        // clear the bits

    // reg = reg | ((baud)<<8);        // left shifting the baud bits

    return reg ;
}

int main() {
    uint32_t reg;
    uint8_t baud;
    scanf("%u %hhu", &reg, &baud);
    printf("%u", set_baud_rate(reg, baud));
    return 0;
}

Step 1 :-

int i,j=0,val=0;

     for(i=8;i<=11;i++){                // iterating the for loop 4 times

        reg = reg & ~(1<<i);            // clearing the bits 

     }

 

Step 2 :-

    for(int k=0;k<4;k++) {            // iterating the for loop 4 times

      val = baud>>k&1;                 // fetching the k th position value form baud and storing in val

       reg = reg | val << (8+k);        // inserting the val in reg by left shifting (8+k) 

    }

Step 3 :-

return reg;                    // returning the reg

 

this logic also will work

 reg = reg & ~(0xF << 8);        // clear the bits

 reg = reg | ((baud)<<8);        // left shifting the baud bits

 return reg ;
Loading...

Input

0 10

Expected Output

2560