Set the Kth Bit

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 40 :- Set the Kth Bit

To set the Kth bit of a given integer, you can use bitwise operations in C++. The "Kth bit" refers to the bit at position K (0-based indexing) from the right, where the rightmost bit is at position 0.

To set the Kth bit, you can use the bitwise OR (|) operator with the mask that has only the Kth bit set (1 at the Kth position and 0 at all other positions).

Here's a C++ program to set the Kth bit of a given integer:

cppCopy code

#include <iostream> int setKthBit(int num, int K) {    int mask = 1 << K;    return num | mask; } int main() {    int num, K;    std::cout << "Enter an integer: ";    std::cin >> num;    std::cout << "Enter the value of K (0-based index): ";    std::cin >> K;    int result = setKthBit(num, K);    std::cout << "Number after setting the " << K << "th bit: " << result << std::endl;    return 0; }

Example output:

mathematicaCopy code

Enter an integer: 5 Enter the value of K (0-based index): 1 Number after setting the 1st bit: 7

In this example, we set the 1st bit (2nd bit from the right, 0-based indexing) of the integer 5. The binary representation of 5 is 101, and after setting the 1st bit, the number becomes 111, which is 7 in decimal.

You can try different values for the input number and the position of the bit (K) to see how the Kth bit is set. Keep in mind that the bit positions are 0-based, so K should be a non-negative integer less than the number of bits in the integer representation (usually 32 or 64 bits, depending on your system).

5. Week2 - Assignments

Comments: 2

profile
@mk.info.work
17-Feb-2024, 10:20 PM

SCIAKU Team please upload 1st video of TREE please please please, please

profile
@na3744
23-Feb-2024, 02:52 AM

I bought this course, it worth it!

profile
@mk.info.work
15-Nov-2023, 10:25 PM

Hi i want to buy this course but you dont have master card payment method please let me know how i can buy it

profile
@sciaku1
11-Jan-2024, 03:23 PM

Dear mk.info.work, Now we have all types of payment options. If you need to purchase just checkout our official website

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?