Do you want the ASCII value of the character or do you want to parse the string contents as a number? Convert String to Char Array in C++ Using a not widely used lib or modifying it yourself is just a hazard game. Either use QString str or (better) const QString &str as parameter. Alternatively, I expect a blabla () function as the following: string str = "Hello"; const unsigned char* ptr = blabla (str); Thanks. Simply use these functions the way they are supposed to be used. Unhandled exception at 0x1022f95b (msvcr80d.dll) in STXM_Control.exe: 0xC0000005: Access violation writing location 0x0064aed8. the pointer was placed because QT gives me error and suggest to do that i have error on line const QbyteArray ba: That is no reason to do it like this. If youn want a String object, than you just need to assign the char array to your String object like this myStringObj = dta;. I tried the above methods but it is failing as my project character set should support unicode also, But in that context the text in CString is normal ANSI characters only. Check the. * in order to put inside the signature not unsigned char but qstring directly? if you want to develop code that builds fine on both ANSI/MBCS and Unicode builds), you should use CString, and you should use TCHAR instead of char, and _tcscpy_s instead of strcpy_s: I think that in your original code you defined your g_sXPS8ServerAddress as a char * string, maybe something like this: char g_sXPS8ServerAddress[ MAX_STRING_LENGTH ]; then you should change this definition to (using TCHAR): and your C++ code to copy the buffer into g_sXPS8ServerAddress should be: _countof( g_sXPS8ServerAddress ), // number of elements. you're assigning a pointer to a single character. If Unicode not enabled, below mentioned procedures will work. The second method can be used even if we do not know the length of source string. There are two ways (I know two only)to solve this problem. @shokarta Thanks for contributing an answer to Stack Overflow! Quote>I have this message error : error C2440: 'type cast' : Quote>cannot convert from 'CString' to 'char *'. Yes, I already tried, there is no error message. There is a LPCTSTR operator defined for CString. Why add an increment/decrement operator when compound assignments exist? https://github.com/SergeyBel/AES/blob/master/README.md. main.cpp:25:12: error: cannot initialize return object of type 'unsigned char' with an lvalue of type 'const unsigned char *'. On which line? Any chance you and i can have any deal on that? Python zip magic for classes instead of tuples, Asymptotic behaviour of an integral with power and exponential functions. So, your code will work in both ANSI/MBCS and Unicode builds (Unicode build is the default build settingsince Visual C++ 2005). Apparently type punning with an union is UB so definitely don't do this. Only users with topic management privileges can see it. i need to pass that return value to another function which accepts const char *, i should not change any of the function signature, when i try to convert from CString to const char * it is giving error message saying it is not possible, is there any way to convert CSting to const char *. If you want to avoid reinterpret_cast, then you must avoid the pointer conversion entirely, which is only possible by solving the XY-problem. Invalid conversion from 'const unsigned char*' to 'const char That is because the return value does not match the functions signature. Converting const unsigned Char* to String I need a routine like: std::string nth_word (const std::string &s, unsigned int n) { // return n-th word from the string, n is 0-based // if 's' contains too few words, return "" //. Method 1: Using string::c_str () function. (Ep. If you want a changed signature in a library, especially if it's just one function, the usual way is you write the desired wrapper function and go via that. The strings types that are covered include char *, wchar_t*, _bstr_t, CComBSTR, CString, basic_string, and System.String. We can call this function to get a const char* to the characters in the string. accommodate a string of virtually any size. You should have been able to work out a solution based on the infoin the other posts in this thread. strcpy_s(g_sXPS8ServerAddress, numberOfElements, buf. How to convert string to const unsigned char* ? - C / C++ Convert String to const unsigned char - Arduino Stack Exchange If UNICODE is not defined LPCTSTR and LPCSTR are the same. arduino ide - Cannot convert 'String' to 'uint8_t {aka unsigned char Would it be very dificult to modify those aes. const char* is LPCSTR. The other way round can be done with QByteArray::fromHex(): many thanks for helping, so I have this then: which brings error on line const unsigned char: Quote>It can't debug, and it stop on this line. Seems more like a generic buffer. stoull yabansu 14 Hi, I just want to know if there is a way of converting a string variable into a const unsigned char pointer. e.g. What is the significance of Headband of Intellect et al setting the stat to 19? 2. Not the answer you're looking for? If you need to use ANSI/MBCS (i.e. 1) Two possibly multilevel pointers to the same type may be converted between each other, regardless of cv-qualifiers at each level. How to convert string to const unsigned char* ? This article shows how to convert various Visual C++ string types into other strings. Site design / logo 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA. str = "1234567891234567" unsigned char* unsignedStr = ConvertStrToUnsignedCharPointer (str); str1 = ConvertUnsignedCharToStr (unsignedStr); Please include an example string from the servers answer to the request. Using Arduino Programming Questions gauravntpl August 16, 2017, 12:58pm 1 In the code I attached what I am trying to do is to save the "String password = "1234567890"; to EEPROM and than reading it from EEPROM.And after reading it from EEPROM I am converting it into "const char* pass2". Is there a good way to convert from unsigned char* to char*? Over the years I have found it's often a good idea to write wrapper functions/classes for more or less every external library one uses, for all sorts of reasons. I find it odd that a function expecting a C-string would want unsigned chars. Heck, I don't even call the Qt classes/methods directly, I tend to provide wrappers for all of them! There is a LPCTSTRoperator defined for CString. The correct way is to use reinterpret_cast. Your browser does not seem to support JavaScript. Can I still have hopes for an offer as a software developer. For skilled one it could be matrer of several minutes only :/. Connect and share knowledge within a single location that is structured and easy to search. Implicit conversion from char** to const char**, convert String to type const char* using Arduino. Edit BTW: I would suggest to not use those old-style C arrays (like char/TCHAR something[MAX_LENGTH] and related old-style C functions, like strcpy_s), but insteadI would use CString (or CStringA or CStringW if you want to make it explicit that you need an ANSI/MBCS or Unicode string). Generally problem comes when Unicode characterset was enabled in your project. The CStringA meythod works, but only because of the (dangerous IMHO) conversion feature build into CString.I would just do: What reply? In all cases, a copy of the string is made when converted to the new type. unsigned char *out = aes.EncryptCBC(StringToChat(plain), BLOCK_BYTES_LENGTH, StringToChat(key), StringToChat(iv), len); @aha_1980 stoul Why? Unsolved Qstring to unsigned char conversion function Would it be very dificult to modify those aes. ChatGPT) is banned, Testing native, sponsored banner ads on Stack Overflow (starting July 6). Issues converting an uint32_t into a char* In particular, only const_cast may be used to cast away (remove) constness or volatility. This forum has migrated to Microsoft Q&A. When I debug this programm, it stop on the. But this has potential overhead, so consider whether avoiding reinterpret_cast is worth it. Converting a string to an const unsigned char* - C / C++ error: array initializer must be an initializer list or string literal. and using this function to convert it to QString: now I am trying to figure out SAME function to convert the QString again to unsigned char. When are complicated trig functions used? Probably not. If we have predefined string length, then we can use this method. To strictly answer your question, there's this way: Is this any better than a reinterpret_cast? Post a small, complete example of code which causes the error. ). I have variable input type const std::string&: Now I need to convert this to const unsigned char* because this is the input of the function. Science fiction short story, possibly titled "Hop for Pop," about life ending at age 30. If you only need an iterator to unsigned char and not necessarily a pointer, then you could use, You could change the function that expects. By clicking Accept all cookies, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy. Converting from C++ string to unsigned char* and back Your code should look like this: If your program is in UNICODE and your function is not, then you might try reading yourCString into a buffer in BYTE(s) and then casting the buffer to a NON-Unicodechar*. Better explain first why you need const unsigned char * at all, then we can find a solution. I know its not nice to ask for such a modification, but this would be extreme helpfull :(. Suppose if we have a string larger than MAX_LENGTH, then this method will fail to copy. String to const char* using "string.c_str ();" Tested solution: Since gcc disallows conversion unsigned char* to const char* and vice versa, I therefore replaced methods EVP_PKEY_CTX_set1_pbe_pass and EVP_PKEY_derive params out.data() and password.data() cast to const char* and unsigned char*. If you want to use security functions, you should stick with well known and good tested libraries like openssl. Unitl now I have correct code for converting: This works well, but in clang I got a warning: What is the correct way to change a string or const char* to const unsigned char*? Convert std::string to const char* in C++ This post will discuss how to convert a std::string to const char* in C++. Looks like your connection to Qt Forum was lost, please wait while we try to reconnect. Is there any reason you cannot do this for your usage? Cannot convert 'const char*' to 'unsigned char* Convert a std::string to char* in C++ @shokarta said in Qstring to unsigned char conversion function: can you please show the function signature of that function? Asking for help, clarification, or responding to other answers. i have one function which returns CString object. 587), The Overflow #185: The hardest part of software is requirements, Starting the Prompt Design Site: A New Home in our Stack Exchange Neighborhood, Temporary policy: Generative AI (e.g. None of these parameters is const, so that means the function can modify in, key, and iv (not sure if it does modify these parameters, but it could). What are the advantages and disadvantages of the callee versus caller clearing the stack after a call? Quote>Suppose if we have a string larger than MAX_LENGTH, then this method will fail to copy. - SergeyA Sep 8, 2021 at 14:08 Add a comment 2 Answers Sorted by: c++ - How to convert string to const unsigned char* without using (string::c_str () converts the string to a signed char) As noted by Juha, a reinterpret_cast is safe and fine, but a question is whether you must convert to unsigned char const * (I presume that you want to preserve the constness! To subscribe to this RSS feed, copy and paste this URL into your RSS reader. The c_str () function is used to return a pointer to an array that contains a null-terminated sequence of characters representing the current value of the string. - Ignacio Vazquez-Abrams. while ((*p++ = *_SRC++) != 0 && --available > 0). std::cout << c; return 0; } Download Run Code. cannot convert 'String' to 'uint8_t {aka unsigned char}' in initialization. strcpy_s(g_sXPS8ServerAddress, numberOfElements, buf); Instead, if you want to code in a Unicode-neutral format (i.e. 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. the function is loaded by unsigned char: as well as it outputs the encrypted string in unsigned char, Hoewer because its a huge function which i understand just on basic logical concept i prefer not to use modify the function to insert string instead of char, as well as output, so i would prefer to convert it (i will be using this on many places, therefore the function is desired). Also, https://github.com/SergeyBel/AES/blob/master/README.md shows how to use the functions. Accessing inactive union member and undefined behavior? How can I learn wizard spells as a warlock without multiclassing? it is supposed to convert it to hex Do you mean that the string "1234" needs to become the number 0x1234? But if we enable Unicode in the project, then the above mentioned methods will not work. There are many replies in this thread, not all of which will work in a Unicode build, which is what you should always be using. That said, I'm not even sure if Qt SLL would provide something useful for you. Consider this: uint32_t payload = 0x00323130; The first line initializes a 32 bit int to a specific value, 0x00323130 in hex. Convert String to const unsigned char coderx06 September 25, 2021, 12:46pm 1 String abc ="0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff"; const unsigned char displaydata []= {reinterpret_cast<const unsigned char*> (abc.c_str ())}; display.drawBitmap (displaydata, startX, startY, bmpWidth, bmpHeight, GxEPD_WHITE); Some options: If you cannot change the type of input and do need a unsigned char* and you still must avoid reinterpret cast, then you could create the std::basic_string from the input using the transform view. You can only copy the result into a buffer provided from outside. if I get it right, all you want to do is to convert the array plain[] to a hexadecimal string. Is it legal to intentionally wait before filing a copyright lawsuit to maximize profits? basicaly i hae dowloaded and used huge function to AES encode and decode string.