"Mike Wahler" <mkwahler@mkwahler.net> wrote in message
news:<x4t_b.6318$aT1.4289@newsread1.news.pas.earth link.net>...[color=blue]
> "Aman" <aman@techie.com> wrote in message
> news:4069be0f43c5d3619e70e2c68cc331c1.26421@mygate .mailgate.org...[color=green]
> > wrote this piece of code on SunOS 5.9 , compiler g++ 2.95.3[/color][/color]
[color=blue][color=green]
> > trying to see the byte order of an int or short int by converting to
> > char*. doesn't work. the char* cpt doesn't seem to be initialized
> > !!. why would that be?[/color][/color]
[color=blue]
> It is.[/color]
[color=blue][color=green]
> > int main()
> > {
> > int x=0x01020304 ;
> > int* ipt = &x ;
> > cout << "ipt : "<< hex << ipt << endl ; // ok ---
> > char* cpt = reinterpret_cast<char*>(ipt) ;
> > cout << "cpt : " << hex << cpt <<endl ; // NO output for cpt !!![/color][/color]
[color=blue]
> The stream inserter (<<) for type 'char*' interprets the argument as a
> pointer to a 'C-style' string (zero terminated array of char).
> e.g.
> char *p = "hello";
> cout << p << '\n'; /* prints "hello" */[/color]
[color=blue]
> One of two things is happening:[/color]
[color=blue]
> - sizeof(int) on your system is four bytes, in which case none
> of them has a value of zero, producing 'undefined behavior', since
> cout<< will run off the end of your array.[/color]
This is his case. Doubtlessly, x is followed fairly soon by a byte
containing 0, because he doesn't get a crash, nor see any output.
(Also, the characters '\001', '\002', '\003'and '\004' don't cause any
visual display.)
[color=blue]
> -sizeof(int) is more than four bytes, in which case some of them
> have zero value, and it appears that on your machine, a zero
> is stored before any of the nonzero bytes, in which case
> cout << cpt terminates before any output.[/color]
[color=blue]
> Try:[/color]
[color=blue]
> for(size_t i = 0; i < sizeof x; ++i)
> cout << hex << cpt[i];
> cout << '\n';[/color]
No better: cpt[i] has type char, so he outputs the byte as a textual
char. Try:
cout << hex << static_cast< int >( cpt[ i ] ) ;
in the loop.
(And of course, the usual disclaimers concerning byte order apply: it
doesn't mean anything, there are more than two possibilities, and if you
need to know, you are doing something grieviously wrong in your code.)
--
James Kanze GABI Software mailto:kanze@gabi-soft.fr
Conseils en informatique orientée objet/
http://www.gabi-soft.fr
Beratung in objektorientierter Datenverarbeitung
11 rue de Rambouillet, 78460 Chevreuse, France, +33 (0)1 30 23 45 16