Jul 19, 2010 at 6:04am UTC
How can I append a byte to a string?
string s = "test";
unsigned char b = 0xff;
I want to append b to s
Last edited on Jul 19, 2010 at 6:54am UTC
Jul 19, 2010 at 6:55am UTC
You know unsigned/signed char are exactly the same except for output? Just cast it to a char*, append the stuff, then cast it back to an unsigned char* if you really need an unsigned char*.
Jul 19, 2010 at 7:23am UTC
So do you think this is ok?
1 2 3 4 5 6 7
typedef unsigned char Byte;
string test = "test" ;
Byte bytes[2] = {0xf5, 0xf3};
test.append((const char *)bytes, 2);
printf("%x\n" , (Byte)test[4]); // prints f5
I just thought if I cast bytes to char* I would lose the most significant bit of each Byte :)
Last edited on Jul 19, 2010 at 7:23am UTC
Jul 19, 2010 at 10:20am UTC
All unsigned chars do is tell the compiler to treat it like an unsigned and ignore 2s compliment rules. So for example:
11111111 = 255 if in an unsigned char
11111111 = -127 if in a signed char
I don't see any reason why it shouldn't.