EmbLogic's Blog

Problem with bit wise operators

I am trying to pad two characters in num and trying to print the num in bit pattern.But I am getting -1 instead of 1;
Output is
for 65 – it should be 01000001
but i am getting 0-100000-1
sample program is :-

/*padding ytwo char*/

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

void char_pad();
void bit_representation( int num);

int main()
{
char_pad();
}
void char_pad()
{
int num =0;
char ch;
printf(“enter first char :”);
ch = getchar();
num = num << 8;
num = num | ch;
printf(“num is : %d\n”,num);
while( getchar() != ‘\n’);

printf(“enter second char :”);
ch = getchar();
num = num <<8;
num = num | ch;
printf(“num is : %d\n”,num);
bit_representation(num);
}

void bit_representation( int num)
{
int temp,loc;
int i,j;
for(i=0; i<4; i++)
{
temp = num;
temp = temp <<(8 * i);

temp = temp >>(24)
printf(“temp is : %d\n”,temp);
for(j=0; j<8; j++)
{
loc = temp;

loc = loc << (24 +j);
loc = loc >>31;
printf(“%d”,loc);
}
printf(“\n”);
}
}

4 Responses to Problem with bit wise operators

  1. msiddarth says:

    could you elaborate more

    • nitin.sharma says:

      In case of signed number,on 32 bit machine having integer length 4 bytes, MSB bit represents the sign.
      in case of positive number it is zero and for negative number it is 1.

      in my case i am trying to print bit representation of a number. and i am getting -1 instead of one even MSB is zero.

  2. kpeswani says:

    num = num << 8;
    the above line in char_pad() is of no use.

    try this for bit representation..
    int i=1;
    int j;
    for(j=0;j<16;j++)
    {
    if(num & i == 1)
    printf("1\n");//or store 1
    else
    printf("2\n");
    i<<=1;
    }

  3. kpeswani says:

    THERE IS SMALL ERROR IN PREVIOUS POST…Pls ignore it

    num = num << 8;
    the above line in char_pad() is of no use.

    try this for bit representation..
    int i=1;
    int j;
    for(j=0;j<16;j++)
    {
    if(num & i == 1)
    printf("1\n");//or store 1
    else
    printf("0\n");
    i<<=1;
    }

Leave a Reply to kpeswani Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>