Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,945 questions

51,887 answers

573 users

How to replace a bit of an integer at a specified position from another integer in C

1 Answer

0 votes
#include <stdio.h>

void print_bits(int n, int size) {
    for (int i = 1 << (size - 1); i > 0; i = i / 2) {
        (n & i) ? printf("1") : printf("0");
    }
}


int main() {

    int a = 15, b = 10, pos = 2; // form right

    print_bits(a, 4);
    printf("\n");

    print_bits(b, 4);
    printf("\n");

    int bit_at_pos = (b >> pos) & 1;
    printf("bit_at_pos = %d\n", bit_at_pos);

    if (bit_at_pos == 1) {
        bit_at_pos = bit_at_pos << pos;
        a |= bit_at_pos;
    }
    else {
        int flag = 255; // FF = 11111111
        bit_at_pos = 1 << pos;
        flag = flag ^ bit_at_pos;
        a &= flag;
    }

    printf("a = %d\n", a);
    print_bits(a, 4);

    return 0;
}




/*
run:

1111
1010
bit_at_pos = 0
a = 11
1011

*/

 



answered May 17, 2023 by avibootz
edited May 19, 2023 by avibootz

Related questions

...