[HH] c++ strings?

Jerry Feldman gaf at blu.org
Sat Dec 15 11:19:02 EST 2012


On 12/13/2012 06:33 PM, Greg London wrote:
> Hmm. C++ is NOT helping here.
>
>    char mybyte=0x52;
>    int myint=0x52;
>
>    cout<<"byte->"<<std::hex<<mybyte<<"<-byte"
>        <<"int->"<<std::hex<<myint<<"<-int"<<endl;
>
>    output is:: byte->R<-byte  int->52<-int
>
>
> It wants to print any 8 bit type, signed or unsigned, as a character,
> even if there's a std::hex in front of it.
>
> Is there an easy fix for this?
>
> I could fake it out by converting the byte to an int,
> and then masking the upper bits I suppose.
>
> But it makes dealing with 8 bit data a bit of a pain.
>
> Greg
>
>
>
>> That's it.
>> Thanks!
>>
>>
>>> Try this:
>>> ss << "actual=0x" << std::hex << actual << " expected=0x" << std::hex <<
>>> expected << " " << msg;
>>>

cout<<"byte->"<<std::hex<<mybyte<<"<-byte"
       <<"int->"<<std::hex<<myint<<"<-int"<<endl;

In this case, mbyte is a char, and the value of 0x52 is 'R'.
Solution cast the byte to an int.

cout<<"byte->"<<std::hex<<|static_cast<int>(|mybyte)<<"<-byte"
       <<"int->"<<std::hex<<myint<<"<-int"<<endl;

Here is an interesting one for you:
#include <iostream>
using namespace std;

int main()
{
 
  int a = -2;
  unsigned b = 1;
  long result;
  result = a * b;
  cout << "Result is " << result << " or 0x" << std::hex << result << "\n";
  return 0;
}
In the above example, the result is -2 if compiled on a 32-bit system,
and 4294967294 if compiled on a 64-bit system. The issue is that the
expression, a + b, becomes an unsigned 32-bit integer expression, so
when the result of the expression is assigned to result, there is no
sign extension. In the 32-bit environment, result would be 32-bits, with
the high order bit set.
The hex result in both is the same: 0xfffffffe.

-- 
Jerry Feldman <gaf at blu.org>
Boston Linux and Unix
PGP key id:3BC1EB90 
PGP Key fingerprint: 49E2 C52A FC5A A31F 8D66  C0AF 7CEA 30FC 3BC1 EB90


-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 545 bytes
Desc: OpenPGP digital signature
URL: <http://lists.blu.org/pipermail/hardwarehacking/attachments/20121215/171c5d99/attachment.sig>


More information about the Hardwarehacking mailing list