×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to read a byte and print bits between given positions

Here, we are going to learn how to read a byte and print bits between given positions in C programming language?
Submitted by Nidhi, on July 31, 2021

Problem statement

Read an 8-bit binary number as a string, then print the bits between given positions using C program.

C program to read a byte and print bits between given positions

The source code to read a byte and print bits between given positions is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to read a byte and
// print bits between given positions

#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[])
{
    int p1 = 0;
    int p2 = 0;
    int i = 0;
    char bytes[9];

    printf("Enter the BYTE: ");
    scanf("%[^\n]s", bytes);

    if (strlen(bytes) < 8) {
        printf("please enter 8-bits\n");
        return 0;
    }

    printf("\nEnter the positions p1 and p1: ");
    scanf("%d%d", &p1, &p2);

    printf("\nBits between positions %d and %d are: ", p1, p2);
    for (i = p1; i <= p2; i++)
        printf("%c ", bytes[i]);

    printf("\n");

    return 0;
}

Output

RUN 1:
Enter the BYTE: 11001100

Enter the positions p1 and p1: 2 7

Bits between positions 2 and 7 are: 0 0 1 1 0 0 

RUN2:
Enter the BYTE: 10101010

Enter the positions p1 and p1: 0 6

Bits between positions 0 and 6 are: 1 0 1 0 1 0 1 

RUN 3:
Enter the BYTE: 10010011

Enter the positions p1 and p1: 3 7

Bits between positions 3 and 7 are: 1 0 0 1 1

Explanation

Here, we read the 8-bit binary number and printed the bits of the number between two given positions on the console screen.

C Bitwise Operators Programs »

Related Programs

Comments and Discussions!

Load comments ↻





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