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 a number at a specified position from another number in C

1 Answer

0 votes
#include <stdio.h>

void replace_bit(int *first, int second, int pos) {
    int bit_at_specified_pos = (second >> pos) & 1;
	
	if (bit_at_specified_pos == 1) {
		bit_at_specified_pos = bit_at_specified_pos << pos;
		*first |= bit_at_specified_pos;
	}
	else { 
		int all_bits_1 = 255;
		bit_at_specified_pos = 1 << pos;
		// set the specified position bit to 0 
		all_bits_1 = all_bits_1 ^ bit_at_specified_pos;
		*first &= all_bits_1;
	} 
}

int main()
{
    int first = 7;  // 0111
    int second = 8; // 1000
    int pos = 3;

	replace_bit(&first, second, pos);
	printf("%d\n", first); // 1111
	
	
	first = 7;   // 0111
    second = 11; // 1011
    pos = 2;

	replace_bit(&first, second, pos);
	printf("%d\n", first); // 0011
	
    return 0;
}

  
  
  
/*
run:
  
15
3
  
*/

 



answered Dec 21, 2023 by avibootz

Related questions

1 answer 143 views
143 views asked Mar 19, 2019 by avibootz
1 answer 146 views
1 answer 199 views
1 answer 212 views
...