简体   繁体   中英

How to convert from 'const char [9]' to 'const unsigned char *'

I'm trying the code mentioned here :

std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
}

And pass: base64_encode("mystring", 8) .

It shows a type conversion error:

error C2664: 'base64_encode' : cannot convert parameter 1 from 'const char [9]' to 'const unsigned char *

I just came across this post and wanted to clarify a bit for anyone else trying to base64 encode a string. The code referred to by the original poster comes from the web page: http://www.adp-gmbh.ch/cpp/common/base64.html . If you go to the author's page and look under the "The test file" section you will see exactly how the author recommends the code to be used.

const std::string s = "test string" ;
std::string encoded = base64_encode(reinterpret_cast<const unsigned char*>(s.c_str()), s.length());

I tried it in my program and it seems to work perfectly.

I don't think you can have string literals using unsigned char s. The easiest way to create a sequence of unsigned char s from a string literal is probably

char const* literal = "hello";
std::vector<unsigned char> ustr(literal, literal + std::strlen(literal));
unsigned char const* ustrptr = ustr.data();

Obviously, the logic could be encapsulated into a suitable function calling base64_encode() .

The alternative is to just reinterpret_cast<unsigned char const*>("hello") but I'm personally not a big fan of this approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM