C program to print the range of fundamental data types using bitwise operators

Here, we are going to learn how to print the range of fundamental data types using bitwise operators in C programming language?
Submitted by Nidhi, on July 24, 2021

Problem statement

Here, we will create two user-defined functions to print the range of signed and unsigned data types.

C program to print the range of fundamental data types

The source code to print the range of fundamental data types using bitwise operators is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to print the range of fundamental data types
// using bitwise operators

#include <stdio.h>

#define SIZE(n) sizeof(n) * 8

void SizeOfSignedNum(int num)
{
    int min = 0;
    int max = 0;
    int tmp = 1;

    while (num != 1) {
        tmp = tmp << 1;
        num--;
    }

    min = ~tmp;
    min = min + 1;
    max = tmp - 1;
    printf("%d to %d", min, max);
}

void SizeOfUnsignedNum(int num)
{
    int min = 0;
    int max = 0;
    int tmp = 1;

    while (num != 0) {
        tmp = tmp << 1;
        num--;
    }

    min = 0;
    max = tmp - 1;
    printf("%u to %u", min, max);
}

int main()
{
    printf("\nRange of int: ");
    SizeOfSignedNum(SIZE(int));

    printf("\nRange of unsigned int: ");
    SizeOfUnsignedNum(SIZE(unsigned int));

    printf("\nRange of char: ");
    SizeOfSignedNum(SIZE(char));

    printf("\nRange of unsigned char: ");
    SizeOfUnsignedNum(SIZE(unsigned char));

    printf("\nRange of short: ");
    SizeOfSignedNum(SIZE(short));

    printf("\nRange of unsigned short: ");
    SizeOfUnsignedNum(SIZE(unsigned short));

    printf("\n");
    return 0;
}

Output

Range of int: -2147483648 to 2147483647
Range of unsigned int: 0 to 4294967295
Range of char: -128 to 127
Range of unsigned char: 0 to 255
Range of short: -32768 to 32767
Range of unsigned short: 0 to 65535

Explanation

In the above program, we created three functions SizeOfSignedNum(), SizeOfUnsignedNum(), and main(). The SizeOfSignedNum() function is used to get the range on signed datatypes. The SizeOfUnsignedNum() function is used to get the range on unsigned datatypes.

In the main() function, we print the range of signed and unsigned data types by calling SizeOfSignedNum() and SizeOfUnsignedNum() functions on the console screen.

C Bitwise Operators Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.