CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com

1. Join Date
Feb 2022
Posts
38

## New with C programming, question about a loop situation

Hi all,

I'm new to the C language, trying to do an exercice where I have to print the "fifth" bit of a given number (0 to 255).The condition of this exercice is to not use operators of affectation (such as >>x or <<x, etc.).

I need to do it with modulo and divisions.

I'm really blocked, tried many things, also searched for solutions on the web, but no success so far. If anyone could
guide threw, I would be thankful as heck.

Pasting my poorly written code, then I will do a comment as what is my idea behind this.

int main(void)

{

int number_user;
int bit;
int i;

printf("Please put an integer between 0 and 255: ");
scanf("%d", &number_user);

i = 0;

while (i <= 4)

{

number_user /= 2;
i++;
}

bit = number_user % 2;

printf ("your fifth bit is %d: \\n", bit);

return EXIT_SUCCESS;
}

2. Member +
Join Date
Feb 2017
Posts
673

## Re: New with C programming, question about a loop situation

You have not explained what is wrong, but your code effectively shifts the input integer five times to the right and then extracts the rightmost bit. For example, given input 32, which has a binary representation of 100000, the code will return a 1. Whether you call this bit the fifth or the sixth depends on whether you call the rightmost bit the zeroeth or the first.

3. ## Re: New with C programming, question about a loop situation

Code:
```#include <stdio.h>

int main() {
for (unsigned i = 0; i < 255; ++i)
printf("The fifth bit of %u is %u\n", i, (i / 16) % 2);
//printf("The fifth bit of %u is %u\n", i, (i >> 4) & 1);	// Using bits (1)
//printf("The fifth bit of %u is %u\n", i, (i & 16) == 16);	// Using bits (2)
}```
Last edited by 2kaud; August 14th, 2022 at 10:57 AM.

4. Join Date
Feb 2022
Posts
38

## Re: New with C programming, question about a loop situation

@wolle thank you so much for your response and suggestion

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•