Question

S4.1) Write C code to set all odd bits (b1, 63, b5, b7) in the uint_8 variable PORT. All other bits should not be changed. S4
0 0
Add a comment Improve this question Transcribed image text
Answer #1

1. To set the bit we use bitwise OR operator because 0 | 0 = 1 and 1 | 0 = 1. So for setting a specific bit we use shift operator.

2. To set the bit we use bitwise OR operator because 0 & 0 = 0 and 1 & 0 = 0. So for clearing a specific bit we use shift operator.

3. To toggle the bit we use bitwise XOR operator because 0 ^ 1 = 1 and 1 ^ 1 = 0. So for toggling a specific bit we use shift operator.

Code:

//you can use int instead of unit8_t.

#include<stdio.h>

#include<stdint.h>

//function to set odd bits.

uint8_t set(uint8_t n){   

    for(uint8_t i=1;i<=8;i+=2){

        n = (n | (1 << (i - 1)));

    }

    return n;

}

//function to clear b3,b4,b5 bits.

uint8_t clear(uint8_t n){

    for(uint8_t i=3;i<=5;i++){

        n = (n & (~(1 << (i - 1))));

    }

    return n;

}

//function to toggle even bits.

uint8_t toggle(uint8_t n){

    for(uint8_t i=2;i<=8;i+=2){

        n = (n ^ (1 << (i - 1)));

    }

    return n;

}

int main()

{

    uint8_t n = 6;

    printf("%d with odd bist Set: %d\n", n, set(n));

    printf("%d with bits b3,b4,b5 clear: %d\n", n, clear(n));

    printf("%d with even bits toggle: %d\n", n, toggle(n));

    return 0;

}

Screenshot of code:

1 #include<stdio.h> #include<stdint.h> 2 3 4 5 // function to set odd bits. uint8_t set(uint8_t n){ for(uint8_t i=1;i<=8;i+=2

Output :

6 with odd bits Set: 87 6 with bits b3, 64, b5 clear: 2 6 with even bits toggle: 172

Add a comment
Know the answer?
Add Answer to:
S4.1) Write C code to set all odd bits (b1, 63, b5, b7) in the uint_8...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT