This whole discussion exemplifies one of my pet peeves about C++ practitioners. C++ is a superset of C, thus, all the constructs available in C are also available in C++.

A simple printf or snprintf would have truncated this discussion quickly.

printf("byte->%02x<-byte int->%02x<-int", (unsigned int) mybyte,  myint);

In both C and C++ you need to take care that "char" is a signed byte, i.e. anything over 0x7F will be a negative number and any conversion to an integer will sign extend and make it 0xffffff - something

On 12/15/2012 11:19 AM, Jerry Feldman wrote:
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.



_______________________________________________
Hardwarehacking mailing list
[email protected]
http://lists.blu.org/mailman/listinfo/hardwarehacking

_______________________________________________
Hardwarehacking mailing list
[email protected]
http://lists.blu.org/mailman/listinfo/hardwarehacking

Reply via email to