c++ - How do I output an unsigned char* to file without reinterpret_cast -
i have unsigned char*
filled characters not ascii example: `
¤Ýkgòd–ùë$}ôkÿuãšj@Äö5Õne„_–Ċ畧-ö—rs^hÌvÄ¥u` .
if reinterpret_cast
, i'll lose characters if i'm not mistaken because they're not ascii. i've searched everywhere solutions require sort of casting or conversion alter data. here's have, doesn't work.
unsigned char* ciphertext = cipher->encrypt(stringtest); string cipherstring(reinterpret_cast<char*>(ciphertext)); //<-- @ point data changes in debugger outputfile.open(outfile); outputfile.close();
you're not calling string
constructor should calling. instead of 1 takes single char *
argument, should call 1 takes 2 arguments - char *
, length.
basic_string( const chart* s, size_type count, const allocator& alloc = allocator() );
to use in example
unsigned char* ciphertext = cipher->encrypt(stringtest); size_t ciphertextlength = // retrieve api allows string cipherstring(reinterpret_cast<char*>(ciphertext), ciphertextlength); outputfile.open(outfile); // assuming outputfile ofstream outputfile << cipherstring; outputfile.close();
note debugger might still indicate truncated string depending on how it's interpreting string
's contents. if open output file in editor , inspect bytes should see expected result.
as remylebeau mentions in comments, if don't need std::string
other purpose, don't need create it, write ofstream
directly.
outputfile.open(outfile); outputfile.write(reinterpret_cast<char*>(ciphertext), ciphertextlength); outputfile.close();