We help IT Professionals succeed at work.
Get Started

The bitwise OR in C

John Kruijt
John Kruijt asked
on
160 Views
Last Modified: 2020-01-20
Hi there, I'm new in C and using a downloaded tutorial to practice and learn. Heading up to the 17th chapter I have a question I can't find an answer to.
The exercise is showing me the use of the bitwise OR:
#include <stdio.h>
#define SET 32

char *binbin(int n);

int main()
{
    int bor, result;

    printf("Type a value from 0 to 255: ");
    scanf("%d",&bor);
    result = bor | SET;
 
    printf("\t%s\t%d\n",binbin(bor),bor);
    printf("|\t%s\t%d\n",binbin(SET),SET);
    printf("=\t%s\t%d\n",binbin(result),result);
    return 0;
}

char *binbin(int n)
{
    static char bin[9];
    int x;

    for (x=0;x<8;x++)
    {
        bin[x] = n & 0X80 ? '1' : '0';
        n << 1;
    }
    bin[x]='\0';
    return(bin);
}

Open in new window

When I run this and I enter a value of less or equal to 95, I get this result:
Type a value from 0 to 255: 95
        01011111        95
|       00100000        32
=       01111111        127

Open in new window

When I enter a value greater then 95, the outcome is:
Type a value from 0 to 255: 96
        01100000        96
|       00100000        32
=       01100000        96

Open in new window

In first I thought the binbin function is giving the wrong output. To test that I added the next line directly after the bitwise OR
printf("This is the result from bitwise OR: %d\n",result);

Open in new window

Running again, it's now clear that the outcome of the bitwise OR can't get higher then 127.
result = bor | SET;

Open in new window

I do understand the 127 in relation to the binary context, but how thus this limitation exist?
What do i have to change to let the bitwise OR give a result higher then 127?
Comment
Watch Question
CERTIFIED EXPERT
Commented:
This problem has been solved!
Unlock 1 Answer and 11 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant

An Experts Exchange subscription includes unlimited access to online courses.

Get Started
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE