Usenet.com

www.Usenet.com

Group Index

Comp Thread Archive from Usenet.com

<-- __Chronological__ --> <-- __Thread__ -->

Re: Bitwise Complement Question



(I am using gcc 2.95.3 and turbo c++ 1.01)

in gcc an int is 4 bytes long
in turbo c an int is 2 bytes.

(try adding the line
printf("The size of an int is %d\n",sizeof(int));
to your code to see this)

so in gcc

x is  0000 0000 0000 0000 0001 0000 1110 0001  <-spaced at hex digits
~x is 1111 1111 1111 1111 1110 1111 0001 1110
and printing as an unsigned int gives 4294962974.

if you changed the line to

printf("   ~x returns: %6u, i.e., 0X%04X (signed %d)\n", ~x,~x,~x);

you'll get signed -4322
 --check the section [I hope there's one] on
2-compliment representation of negative numbers.

in turbo c,

x is  0001 0000 1110 0001
~x is 1110 1111 0001 1110
so you get what the book shows

note also that you are using -signed- ints but
printing them as unsigned (%u). In general
it's a good idea to make these match, use
%u to print unsigned int and %d to print
signed int or know the reason you're not.

change
int x,y,z;
to
unsigned short x,y,z;
and calculate
z=~x;
before printing
printf("   ~x returns: %6u, i.e., 0X%04X\n", z,z);

-or-

cast ~x as a unsigned short
printf("   ~x returns: %6u, i.e., 0X%04X\n",
     (unsigned short)~x,(unsigned short)~x);
(not so good an idea unless you *know* x cannot exceed the range of an
unsigned short)

and you'll get the expected results.

there is some other fussiness about integral promotion --if you
printf a short using %u you'll get it printed as a short, but
if you do an operation, like ~x, x get promopted to an int, then
complimented and an int is returned, so it will print as an int.
you can (unsigned short) ~x

> > I got a very different result
> > from that listed in the book.
In this group ``The book'', without other quantifiers, means
"The C programming language" by B. Kernigham D. Ritchie :)
Get a copy if you can.

> > I should mention that the book seems to lean towards Borland running on
> > Windows
Borland product & manuals seen aware there is an outside world (the
library referce lists which functions are portable to unix), but
DOS/windows people tend not to... (and unix people don't care :)
Nice compilers.

> > Is there something I should
> > be learning about byte ordering or some such?
no, if you are sticking with the std libraries & builtin features byte
ordering shouldn't come up, except maybe in tricksy uses of unions.


Don't reply to spambait1000006 unless you are offering to
help me debug. It results in being E-mailed core files.

  CC





<-- __Chronological__ --> <-- __Thread__ -->


Usenet.com



Please check out one of the premium Usenet Newsgroup Service Providers below for access to Usenet.