How can I convert 0x70, 0x61, 0x73 ... etc to Pas ... etc in C++?

I am using MSVC++ 2010 Express, and I would love to know how to convert

BYTE Key[] = {0x50,0x61,0x73,0x73,0x77,0x6F,0x72,0x64}; 

to "Password" I am having a lot of trouble doing this. :( I will use this knowledge to take things such as...

BYTE Key[] { 0xC2, 0xB3, 0x72, 0x3C, 0xC6, 0xAE, 0xD9, 0xB5, 0x34, 0x3C, 0x53, 0xEE, 0x2F, 0x43, 0x67, 0xCE }; 

And other various variables and convert them accordingly.

Id like to end up with "Password" stored in a char.

6

2 Answers

Key is an array of bytes. If you want to store it in a string, for example, you should construct the string using its range constructor, that is:

string key_string(Key, Key + sizeof(Key)/sizeof(Key[0])); 

Or if you can compile using C++11:

string key_string(begin(Key), end(Key)); 

To get a char* I'd go the C way and use strndup:

char* key_string = strndup(Key, sizeof(Key)/sizeof(Key[0])); 

However, if you're using C++ I strongly suggest you use string instead of char* and only convert to char const* when absolutely necessary (e.g. when calling a C API). See here for good reasons to prefer std::string.

1

All you are lacking is a null terminator, so after doing this:

char Key_str[(sizeof Key)+1]; memcpy(Key_str,key,sizeof Key); Key_str[sizeof Key] = '\0'; 

Key_str will be usable as a regular char * style string.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like