- Bit Operation not working

PDA

View Full Version : Bit Operation not working


Marcia Hon
07-24-2004, 11:22 PM
Hi,
Somehow my bit operation always negates the number.

I have:
int size = 141;
char * packet = (char *) malloc ((sizeof(char));

packet[0] = 141 & 0xff;

Instead of packet being 8d, ie 141, it becomes ffffff8d.
Please help.

Thank you,
Marcia

Frank Hickman
07-24-2004, 11:22 PM
How are you determining your value?

--
Frank

"Marcia Hon" <honm@rogers.com> wrote in message
news:itTXb.60518$Ywc1.13857@news04.bloor.is.net.cable.rogers.com...
> Hi,
> Somehow my bit operation always negates the number.
>
> I have:
> int size = 141;
> char * packet = (char *) malloc ((sizeof(char));
>
> packet[0] = 141 & 0xff;
>
> Instead of packet being 8d, ie 141, it becomes ffffff8d.
> Please help.
>
> Thank you,
> Marcia
>
>
>

Jeff Schwab
07-24-2004, 11:22 PM
Marcia Hon wrote:
> Hi,
> Somehow my bit operation always negates the number.
>
> I have:
> int size = 141;
> char * packet = (char *) malloc ((sizeof(char));
>
> packet[0] = 141 & 0xff;
>
> Instead of packet being 8d, ie 141, it becomes ffffff8d.
> Please help.

Your first problem is that your parentheses are mismatched around
"sizeof". Your second problem is that you're not just printing an
individual char, you're converting it to some larger type first,
probably int. As part of the conversion, the value in your (signed)
char is being sign-extended. Try using unsigned char's for raw data.

-Jeff