Skip to main content

Featured

C Program to Check Prime Number Using Efficient Logic

  Introduction A prime number is a number that has exactly two distinct positive divisors: 1 and itself. In this program, we check whether a given number is prime or not using a simple and efficient logic. This type of program is commonly used in mathematics, competitive programming, and basic algorithm learning for beginners in C programming. Problem Statement The task is to write a C program that determines whether a given integer is a prime number or not. The program takes a single integer input from the user and analyzes its divisibility. If the number has no divisors other than 1 and itself, it should be identified as a prime number; otherwise, it is not prime. This problem is important in number theory and has practical relevance in areas such as cryptography, data validation, and algorithm design.  Algorithm / Logic Explanation To check whether a number is prime, we need to verify that it is not divisible by any number other than 1 and itself. The algorithm follows a si...

Nibble Swapping in C (Hexadecimal Input) in C

Nibble Swapping in C

๐Ÿ”ถ Nibble Swapping in C (Hexadecimal Input)

#include<stdio.h>
int main( )
{
    unsigned int num;
    printf("Enter the number(in hex):");
    scanf("%x",&num);
    num = num & 0xFF;
    unsigned int swapped = ((num & 0x0F) << 4) | ((num & 0xF0) >> 4);
    printf("After swapping number is: %02X\\n", swapped);
    return 0;
}
  

๐Ÿ“˜ Explanation:

This C program swaps the upper and lower 4-bit nibbles of an 8-bit hexadecimal number.

๐Ÿ”น `scanf("%x", &num);` reads a hexadecimal value.
๐Ÿ”น `num & 0xFF` ensures the value is within 8 bits.
๐Ÿ”น `(num & 0x0F) << 4` moves the lower nibble to the upper nibble position.
๐Ÿ”น `(num & 0xF0) >> 4` moves the upper nibble to the lower nibble position.
๐Ÿ”น The final result is obtained by combining both using bitwise OR (`|`).
๐Ÿ”น `%02X` prints the swapped result in uppercase hexadecimal format with leading zero if needed.

๐Ÿ” Sample Output:

Enter the number(in hex):3C
After swapping number is: C3

Enter the number(in hex):F0
After swapping number is: 0F
    

๐Ÿท️ Keywords:

bitwise operations in C, swap nibbles C, C program hex input, 8-bit nibble swap, binary logic in C, nibble masking, hex manipulation

Comments

Popular Posts

๐ŸŒ™