-1
int main() {

    unsigned int nr, mask;

    printf("nr = ");   //for eg. if i use number 11111111 or 00111111 it prints 0. 
    scanf("%hu", &nr);

    if ((nr & 0b00001000) == 0)
        printf("0\n\n");
    else
        printf("1\n\n");

mask = 0b00001000;

    if (nr & mask)
        printf("1\n");
    else
        printf("0\n");

    printf("%x", nr);

    return 0;
}

I can set a reset a bit using a mask like this 00001000 & nr(10101010) with the "1" placed so the 4th bit will be rest, but again it doesn't work ( I don't know why). But I have no idea how to print the number after.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
Bufni
  • 1
  • 2
    C and C++ are different language. Would you mind choosing one? – MikeCAT Oct 22 '20 at 14:30
  • I would like in c. I looked at that, but I wanted to try this way, if it can be done. I am very new to programing so yeah – Bufni Oct 22 '20 at 14:32
  • *"with the "1" placed so the 4th bit will be rest"* - `1 & 1` is still `1`. You might want to re-think that. – Marco Bonelli Oct 22 '20 at 14:32
  • `scanf("%hu", &nr);` invokes *undefined behavior* due to type mismatch: `%hu` expectes `unsigned short*`, but passed thing is `unsigned int*`. – MikeCAT Oct 22 '20 at 14:34
  • if I change it to unsigned short nr, mask It still doesnt work with numbers like 11111111 or 00111111 – Bufni Oct 22 '20 at 14:39

1 Answers1

1

scanf() don't have options to read binary string, so you will have to read as string and do conversion by yourself.

For example (error checking is omitted):

char nr_str[128];
scanf("%127s", nr_str);
nr = 0;
for (int i = 0; nr_str[i] != '\0'; i++) {
    nr = (nr << 1) | (nr_str[i] - '0');
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • If i try using the number 10001000 and mask 00001000 it works. – Bufni Oct 22 '20 at 14:37
  • @Bufni `10001000` in decimal is `100110001001101001101000` in binary and the 4th bit counted from LSB is `1`. You are (un)lucky! – MikeCAT Oct 22 '20 at 14:48