0

I am beginner to this programming and recently my teacher gave me a homework on swapping two bits in a byte. I could not figure out how to do so i referred to a website where there was an answer for that. The thing is there they gave a fixed input but I want to get input at runtime and swap bits in that.But I am receiving same output for every input

My code is

#include <stdio.h>

int main()
{
    unsigned char data;
    printf("Enter hex number: ");
    scanf("%c",&data);
    unsigned char bit_1 = (data >> 1) & 1;
    unsigned char bit_2 = (data >> 2) & 1;
    unsigned char xor_of_bit = bit_1 ^ bit_2;
    printf("After swapping the bits, data value is: %2X", data ^ (xor_of_bit << 1 | xor_of_bit << 2));
    return 0;
}

My input was 0xA and my ouyput was 30

Baba_yaga
  • 3
  • 5
  • I got some different output for some different input. (I got output `61` for input `a` and output `64` for input `b`) – MikeCAT May 19 '21 at 16:14
  • 2
    The prompt says to enter a hex number, but you're just reading a single character. – Barmar May 19 '21 at 16:15
  • 'scanf("%c",&data);' will not read in an ASCII hex pair. – Martin James May 19 '21 at 16:15
  • @MartinJames Use backticks to mark code blocks in comments. E.g. `scanf("%c",&data);` – Barmar May 19 '21 at 16:16
  • What are your actual inputs and outputs? – Barmar May 19 '21 at 16:17
  • If you are new to programming and especially to bitwise operation, I would advice to first try to solve things without using XOR (`^`), because XOR, while very useful, it is more difficult to follow what it does. You can solve anything with AND and OR (`&`, `|`), so try to do that first, even if the solution is longer. Only then look at what "tricks" you can do with XOR to make it shorter. In this case, you can use `~` and `&` to turn the two relevant bits to zero, and then you can use `|` (along with `&` and `<<`) to turn a bit to one only if needed. – Orielno May 19 '21 at 16:40

0 Answers0