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,890 questions

51,817 answers

573 users

How to find the highest bit set for any given 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 get_highest_bit_set(unsigned int n) {
	int count = -1, i = 0;

	while (n != 0) {
		if (n & 1 == 1) {
			count = i;
		}
		n = n >> 1;
		i++;
	}

	return count;
}

int main() {
	unsigned int n = 48;

	print_bits(n, 8);
	printf("\n");

	int result = get_highest_bit_set(n); // from right 

	if (result == -1) {
		printf("No bit is set"); 
	}
	else {
		printf("Highest set bit = %d", result);
	}

    return 0;
}



/*
run

00110000
Highest set bit = 5

*/

 



answered May 18, 2023 by avibootz

Related questions

...