UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

  • Index
  • » C
  • » int value copied to char .

#1 2007-03-23 09:32 PM

vijraj
Member
Registered: 2006-10-23
Posts: 23

Re: int value copied to char .

Hi all!

I want the value of a short to be copied into a char.I used this program.

int _tmain(int argc, _TCHAR* argv[])
{
	char m;
	unsigned char* charptr;
	unsigned short y = 141;
	
	charptr = (unsigned char*)&y;
	m = *charptr;
	printf("%d\n",y);
	return 0;
}


I want m to be 141.But it shows to be -115.Why?
Any help is appreciated.Thanks.

Offline

#2 2007-03-23 10:02 PM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: int value copied to char .

Because that is the signed char value (141 - 256 = -115).

But how you managed to print -115 with that code, I've no idea, because it prints y, not m.

Also, why the pointer trickery? "m = (char)y;" should do.

Offline

#3 2007-03-23 10:08 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,839
Website

Re: int value copied to char .

That code as posted should output 141 properly, because you are passing "y" to
printf() rather than "m", which I think you wanted...

But, the reason is that your "char"s are presumably signed by default, and since
141 is greater than 127, you're overflowing into the sign bit...  Use "unsigned char"
instead...

But, that wierdness you do with the pointer into your short isn't needed, either...
In fact, that's harmful, in that it'll break on a big-endian system...  All you really need
to do is:

unsigned char m;
	unsigned short y = 141;
	
	m = y;
	printf("y = %d, m = %d\n", y, m);

Offline

#4 2007-03-24 06:39 PM

vijraj
Member
Registered: 2006-10-23
Posts: 23

Re: int value copied to char .

Thanks all.I was using the VS ide to debug and when I put the mouse pointer on m it gave me that value.I fixed it by using unsigned char.Thanks.

Offline

  • Index
  • » C
  • » int value copied to char .

Board footer

Powered by FluxBB