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

2 Comments

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

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

@na3744
na3744 Feb 23, 2024 at 2:52 AM

I bought this course, it worth it!

@mk.info.work
mk.info.work Nov 15, 2023 at 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

@sciaku1
sciaku1 Jan 11, 2024 at 3: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 About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support