Q:

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

Program:

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C solved programs/examples on Bitwise Operators

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to count the number of leading zeros in ... >>
<< C program to round off an integer number to the ne...