C++ cout<<hex issue

Red Squirrel

No Lifer
May 24, 2003
70,592
13,807
126
www.anyf.ca
I wrote a simple function to do a "hex dump" of a string.

void HexDump(string str)
{
int strsize=str.size();

int pos=0;

cout<<flush<<endl;

while(pos<strsize)
{
for(int i=pos;i<pos+16;i++)
{
if(i>=strsize)break;
cout<<flush<< setw(2) << setfill ( '0' )<< hex <<(int)str<<" ";

}
cout<<"\n";
for(int i=pos;i<pos+16;i++)
{
if(i>=strsize)break;

if((int)str < 32 || 126 < (int)str)cout<<". ";
else cout<< str<<" ";
}

pos+=16;

if(pos<strsize)cout<<"\n\n";
}
}


For some reason, the first hex character often has FFFFFF before it. This is random, and screws up the output. Here's an example:




[root@borg uocli]# ./uocli


Connecting...Connected
Sent Packet: 4 bytes
-------------------------------------------------------------------------------

0a 01 01 14
. . . .
-------------------------------------------------------------------------------


Sent Packet: 62 bytes
-------------------------------------------------------------------------------

ffffff80 74 65 73 74 31 32 33 74 65 73 74 00 00 00 00
. t e s t 1 2 3 t e s t . . . .

00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 74
. . . . . . . . . . . . . . . t

65 73 74 31 32 33 74 65 73 74 00 00 00 00 00 00
e s t 1 2 3 t e s t . . . . . .

00 00 00 00 00 00 00 00 00 00 00 00 00 5d
. . . . . . . . . . . . . ]
-------------------------------------------------------------------------------



Authenticating...
Sent Packet: 4 bytes
-------------------------------------------------------------------------------

0a 01 01 14
. . . .
-------------------------------------------------------------------------------


Sent Packet: 4 bytes
-------------------------------------------------------------------------------

0a 01 01 14
. . . .
-------------------------------------------------------------------------------


Reveived Packet: 1 bytes
-------------------------------------------------------------------------------

ffffffa8
.
-------------------------------------------------------------------------------



Press any key to exit



In both cases where this happens, the proceeding 2 chars are the valid hex value that I expect to see. I just don't understand why its randomly throwing those F's there.
 

dighn

Lifer
Aug 12, 2001
22,820
4
81
it's because of sign extention. std::string::eek:perator[] returns char (signed). and 0x80 is 10000000 in binary so when you convert it to int (signed) it gets sign extended

you can try casting to unsigned int instead, or even casting to unsigned char and then unsigned int
 

Red Squirrel

No Lifer
May 24, 2003
70,592
13,807
126
www.anyf.ca
Hmm interesting. That worked. I did this:

cout<<flush<< setw(2) << setfill ( '0' )<< hex <<(unsigned int)(unsigned char)str<<" ";

Seems to work. Thanks!