about ofToHex()....

unsigned char buffer[2];
buffer[0] = 0xAB;
buffer[1] = 0xCD;
string tmp = ofToHex(buffer);
cout<<"tmp: "<<tmp<<endl;

Console results…
tmp: cdab

why is the output of the console “cbab”,not “abcd”?

the output is “cdab” instead of “abcd” because ofToHex() (and the other conversion functions) are built for simple datatypes like char/short/int/float rather than complex datatypes like char[].

so if you do this:

short tmp = 0xABCD;  
cout << ofToHex(tmp) << endl;  

it will print “abcd”. internally, the bytes are stored “backwards” in memory, so they are read out “backwards”. to illustrate:

char a = 0x12; // memory is 12  
short b = 0x1234; // memory is 34 12  
int c = 0x12345678; // memory is 78 56 34 12  

sometimes you want to print out strings in hex, and strings are stored “forwards” instead of “backwards”, so i have overloaded ofToHex(string) and ofToHex(const char*).

string a = "xy";  
cout << ofToHex(a) << endl; // prints 78, 79  
cout << ofToHex("xy") << endl; // prints 78, 79  

These are some of the best additions by the way… I do a lot of GA/GP stuff and my workflow is off the charts because of this.

thanks! i spent a lot of time porting every conversion function i could think of from processing to OF during the ofdev-conference early this year :slight_smile:

Thanks for your reply. and there’s a problem exist:
the returns of serial.readBytes() is an unsigned char * buffer, not short,int etc.

what should i do so that unsigned char[] or unsigned char* is converted to string with form is hex(for example:“abcd”).

I try to use the following method. . But the result is “ffffffabffffffcd”

unsigned char bytesReturned[2];
bytesReturned[0]= 0xAB;
bytesReturned[1]= 0xCD;

unsigned char bytesReadString[3];
memset(bytesReadString, 0, 3);
memcpy(bytesReadString, bytesReturned, 2);

string tmp = ofToHex((const char*)bytesReadString);
cout<<"tmp: "<<tmp<<endl;

Console results…
tmp: ffffffabffffffcd

do it one character at a time. something like this:

unsigned char bytesReturned[2];  
string tmp;  
for(int i = 0; i < 2; i++) {  
  tmp += ofToHex(bytesReturned[i]);  

Thanks again. . . I understand…