question about shift operator

Chris Torek chris at mimsy.UUCP
Tue Nov 8 11:41:51 AEST 1988


In article <192 at libove.UUCP> root at libove.UUCP (Jay M. Libove) writes:
>Looking at the above, I read it to be "shift an n-bit integer n bits left"
>... Now, why is there any question as to the result?

Because different machines implement shift-left differently.

>(One machine test ....

Try a better test.

	#define	BITS_PER_CHAR	8	/* needed below */

	int fn();

	main()
	{
		int x = ~0;
		x <<= fn(sizeof(x));
		printf("result of %d << %d is %d\n", ~0, fn(sizeof(x)), x);
		exit(0);
	}

	/*
	 * You may have to put fn() in a separate file if your compiler is
	 * overly clever.
	 */
	int fn(sz) int sz; { return (sz * BITS_PER_CHAR); }

On the VAX, the result of shifting by the (not known to be constant)
value 32 is the same as the result of shifting by zero, because the VAX
looks only at the 5 lowest order bits of the shift count.  It does this
so that right shifts can be done with negative left shifts.  (Note
that, since this is an arithmetic shift and not a rotate, it still
checks the sign bit of the shift count to see whether to propagate the
sign bit of the original value in a rightward shift.)
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list