use strtol () or strtoul () for example (or strtoull () if you need an unsigned long long) You can easily do this with: QString s = QByteArray(reinterpret_cast
(plain)).toHex() instead your complicated function. unsigned char *out = aes.EncryptCBC(StringToChat(plain), BLOCK_BYTES_LENGTH, StringToChat(key), StringToChat(iv), len); @aha_1980 Using string::c_str function I know its not nice to ask for such a modification, but this would be extreme helpfull :(. Now let's assume that payload was stored in memory at address 0x0100. Issues converting an uint32_t into a char* Science fiction short story, possibly titled "Hop for Pop," about life ending at age 30. Quote>But the disadvantage is string length is restricted to MAX_LENGTH. 1 How exactly is the server giving you the binary data? How can I convert a string to a const unsigned char*? STR34-C. Cast characters to unsigned char before converting to larger Converting const unsigned Char* to String 1) Two possibly multilevel pointers to the same type may be converted between each other, regardless of cv-qualifiers at each level. 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. If idx is not a null pointer, the function also sets the value of idx to the position of the first character in str after the number. char *cstr = str.GetBuffer(str.GetLength()); http://www.codeguru.com/forum/showthread.php?t=85534. Convert string to unsigned integer Parses str interpreting its content as an integral number of the specified base, which is returned as an unsigned long value. - chrisl Sep 25, 2021 at 14:19 With const unsigned char displaydata= {reinterpret_cast<const unsigned char*> (. Check the. - Ignacio Vazquez-Abrams. Is it legal to intentionally wait before filing a copyright lawsuit to maximize profits? Qstring to unsigned char conversion function. If idx is not a null pointer, the function also sets the value of idx to the position of the first character in str after the number. https://forum.qt.io/topic/113070/qt-code-of-conduct. strcpy_s(g_sXPS8ServerAddress, numberOfElements, buf. Im very lost and tried many solutions i found online, nothing worked Can you pleas ehelp me to make new funciton StringToChar() to convert the Qstring into unsigned char? You can use wcstombs() method as below wcstombs(cstr, (TCHAR*)(const TCHAR*)str, MAX_LENGTH); But the disadvantage is string length is restricted to MAX_LENGTH. Find centralized, trusted content and collaborate around the technologies you use most. i have one function which returns CString object. The Arduino reads the data and tramnsmits it over BLE so you can plot the Data on your smartphone. Any chance you and i can have any deal on that? yabansu 14 Hi, I just want to know if there is a way of converting a string variable into a const unsigned char pointer. The other way round can be done with QByteArray::fromHex (): const QString s = "0123456789ABCDEF" ; const . I find it odd that a function expecting a C-string would want unsigned chars. 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. How to: Convert Between Various String Types | Microsoft Learn * in order to put inside the signature not unsigned char but qstring directly? Why? unsigned short i, length;BYTE ByteBuffer [128]={0};TCHAR szCString [256]={0}; wsprintf(szCString,TEXT("%s"),szYourCStringString); i = 0;length = lstrlen(szCString);if (length && length < sizeof(ByteBuffer)){ do{ ByteBuffer=(BYTE)(TCHAR)szCString; }while (++i < length);}, ////SendCharStringToYourFunction((char*)ByteBuffer));//. Do you want the ASCII value of the character or do you want to parse the string contents as a number? ChatGPT) is banned, Testing native, sponsored banner ads on Stack Overflow (starting July 6). Type cast from unsigned const char * to char const *, Converting from C++ string to unsigned char* and back. main.cpp:25:12: error: cannot initialize return object of type 'unsigned char' with an lvalue of type 'const unsigned char *'. https://github.com/SergeyBel/AES/blob/master/README.md. 1 You can do 2 static casts - one to the const void*, second from const void* to const unsigned char* It is also possible that a better container for you would be a vector of unsigned char, rather than std::string. (Keeping the answer for posterity though!). Why add an increment/decrement operator when compound assignments exist? Your code should look like this: CString str; const char* cstr = (LPCTSTR)str; however, I would put it like this: CString str; const TCHAR* cstr = (LPCTSTR)str; Asking for help, clarification, or responding to other answers. Convert unsigned char to String - General - Particle Python zip magic for classes instead of tuples, Asymptotic behaviour of an integral with power and exponential functions. stoul Note the use of _countof to get the correctnumber of elements (expressed in count of char's in ANSI/MBCS builds, and in count of wchar_t's in Unicode builds). Yes, I already tried, there is no error message. 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. char buffer [32]; sprintf (buffer, " {data:%d}", payload); Then send buffer via a function that expects a C string. Yes. Eligibility criteria to become the prime minister of India and what is "office of profit"? On which line? String to const char* using "string.c_str ();" its downloaded and used from here: Thanks for contributing an answer to Stack Overflow! Convert String to Char Array in C++ That said, I'm not even sure if Qt SLL would provide something useful for you. 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. There are two ways (I know two only)to solve this problem. Please download a browser that supports JavaScript, or enable it if it's disabled (i.e. Convert String to const unsigned char - Displays - Arduino Forum Edit * in order to put inside the signature not unsigned char but qstring directly? Convert from std::string to unsigned char* - C / C++ char * ) strings, you should use CStringA instead of CString. void f(const char* s){ std::cout << s << std::endl;}CString str = _T("Testing");f(CT2CA(str)); Suneel:Some of the answers in this thread are wrong, and others seem overly complicated. cannot convert 'String' to 'uint8_t {aka unsigned char}' in initialization. Convert String to const unsigned char - Arduino Stack Exchange There is a LPCTSTRoperator defined for CString. Is religious confession legally privileged? The strings types that are covered include char *, wchar_t*, _bstr_t, CComBSTR, CString, basic_string, and System.String. (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! Quote>Suppose if we have a string larger than MAX_LENGTH, then this method will fail to copy. If you want to avoid reinterpret_cast, then you must avoid the pointer conversion entirely, which is only possible by solving the XY-problem. Using a not widely used lib or modifying it yourself is just a hazard game. But if we enable Unicode in the project, then the above mentioned methods will not work. If youn want a String object, than you just need to assign the char array to your String object like this myStringObj = dta;. Unsolved Qstring to unsigned char conversion function Compliant Solution In this compliant solution, the result of the expression *c_str++ is cast to unsigned char before assignment to the int variable c: What are the advantages and disadvantages of the callee versus caller clearing the stack after a call? Not the answer you're looking for? e.g. ). 1. I'm not an avoid fan of MFC, nor have I used it the last 6 or 7 years, but I seem to recall that you can cast it directly (it should have a user defined conversion operator). @shokarta said in Qstring to unsigned char conversion function: can you please show the function signature of that function? 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 *. How to convert string to const unsigned char* ? yabansu Dec 27 '06 # 1 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 "" //. - SergeyA Sep 8, 2021 at 14:08 Add a comment 2 Answers Sorted by: Way to get unsigned char into a std::string without reinterpret_cast? The returned pointer should point to a char array containing the same sequence of characters as present in the string object and an additional null terminator ('\0' character) at the end. Making statements based on opinion; back them up with references or personal experience. 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. Have you tried this? stoull How do I convert the contents of an unsigned char * to a const char *? Your browser does not seem to support JavaScript. Since you can get the length of the string using str.GetLength(), you can dynamically assign the cstr buffer using new or malloc to. Convert string to unsigned long long Parses str interpreting its content as an integral number of the specified base , which is returned as a value of type unsigned long long . You can only copy the result into a buffer provided from outside. Better explain first why you need const unsigned char * at all, then we can find a solution. while ((*p++ = *_SRC++) != 0 && --available > 0). It returns a const char pointer to the null terminated contents of the string. The correct way is to use reinterpret_cast. We can enable/disable Unicode by changing the Character Set property of the project. 2. To strictly answer your question, there's this way: Is this any better than a reinterpret_cast? const char* c_str () const; If there is an exception thrown then there are no changes in the string. That is because the return value does not match the functions signature. I'd be curious to see the function. How to convert string to const unsigned char* ? - C / C++ 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); basicaly i hae dowloaded and used huge function to AES encode and decode string. std::cout << c; return 0; } Download Run Code. Converting from C++ string to unsigned char* and back The second method can be used even if we do not know the length of source string. Quote>It can't debug, and it stop on this line. Visit Microsoft Q&A to post new questions. Heck, I don't even call the Qt classes/methods directly, I tend to provide wrappers for all of them! Cannot convert 'const char*' to 'unsigned char* Explanation Only the following conversions can be done with const_cast. Probably not. Consider this: uint32_t payload = 0x00323130; The first line initializes a 32 bit int to a specific value, 0x00323130 in hex. But again: you cannot return a pointer to a local variable! 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. arduino ide - Cannot convert 'String' to 'uint8_t {aka unsigned char Using strcpy () function. Alternatively, I expect a blabla () function as the following: string str = "Hello"; const unsigned char* ptr = blabla (str); Thanks. The CStringA meythod works, but only because of the (dangerous IMHO) conversion feature build into CString.I would just do: What reply? Either use QString str or (better) const QString &str as parameter. In C++, the string class provides a member function c_str (). 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*. Fix it please. Site design / logo 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA. rev2023.7.7.43526. How can I learn wizard spells as a warlock without multiclassing? str = "1234567891234567" unsigned char* unsignedStr = ConvertStrToUnsignedCharPointer (str); str1 = ConvertUnsignedCharToStr (unsignedStr); You can use it within the function, but not outside. What is the significance of Headband of Intellect et al setting the stat to 19? strcpy_s(g_sXPS8ServerAddress, numberOfElements, toto); error C2440: 'type cast' : cannot convert from 'CString' to 'char *'. Only users with topic management privileges can see it. NoScript). @shokarta By clicking Accept all cookies, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy. As a result, your viewing experience will be diminished, and you have been placed in read-only mode. If UNICODE is not defined LPCTSTR and LPCSTR are the same. string char constants Share Improve this question Follow edited May 16, 2021 at 11:14 Peter Mortensen 30.9k 21 105 131 asked Dec 7, 2008 at 19:30 user37875 13.9k 9 37 43 2 Instead of: char * writable = new char [str.size () + 1]; You can use char writable [str.size () + 1]; Then you don't need to worry about deleting writable or exception handling. This forum has migrated to Microsoft Q&A. When are complicated trig functions used? This article shows how to convert various Visual C++ string types into other strings. If we have predefined string length, then we can use this method. 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. Any help would be great as I thought adding (String) . Sorry, I missed a star, I meant const unsigned char *plain = reinterpret_cast(ba.constData()); const unsigned char result = reinterpret_cast(ba.constData()); Is a dropper post a good solution for sharing a bike between two riders? This library does not use Qt. Generally problem comes when Unicode characterset was enabled in your project. Converting a string to an const unsigned char* - C / C++ I am also facing the same problem as u had faced.. Can I plz know the solution.. http://www.codeguru.com/forum/showthread.php?t=231165. How to convert a std::string to const char* or char* But this has potential overhead, so consider whether avoiding reinterpret_cast is worth it. Iwould suggest trying this simple MFC-based method of conversion from Unicode: Yes. Spying on a smartphone remotely by the authorities: feasibility and operation, Defining states on von Neumann algebras from filters on the projection lattices. Jun 29, 2015 at 6:38. 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. Quote>If we have predefined string length, then we can use this method. Output: std::string to char*. Let's see an example, You should have been able to work out a solution based on the infoin the other posts in this thread. the local variable is destroyed when you leave the function. if I get it right, all you want to do is to convert the array plain[] to a hexadecimal string. it is supposed to convert it to hex Do you mean that the string "1234" needs to become the number 0x1234? how to convert CString to const char 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). 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: 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. if I get it right, all you want to do is to convert the array plain [] to a hexadecimal string. This topic has been deleted. Invalid conversion from 'const unsigned char*' to 'const char Method 1: Using string::c_str () function. (Ep. When I debug this programm, it stop on the. There is a LPCTSTR operator defined for CString. Is there any reason you cannot do this for your usage? Although it may be too late, thx a lot! If you need to use ANSI/MBCS (i.e. const char* is LPCSTR. 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*? 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*. Convert string to const char* in C++ - thisPointer Context : Data is lying an an sd Card in the arduino. Would it be very dificult to modify those aes. 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. That means, you have to create local buffers for these parameters, and copy the data into the buffers. Ask Question Asked 7 years, 7 months ago Modified 7 years, 7 months ago Viewed 10k times 6 What would be the code to convert an std::string to unsigned char* and back? 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. To learn more, see our tips on writing great answers. return result; Note that you cannot do that! Looks like your connection to Qt Forum was lost, please wait while we try to reconnect. accommodate a string of virtually any size. error: array initializer must be an initializer list or string literal. In all cases, a copy of the string is made when converted to the new type. Post a small, complete example of code which causes the error. you're assigning a pointer to a single character. Would it be very dificult to modify those aes. const_cast conversion - cppreference.com If Unicode not enabled, below mentioned procedures will work. To subscribe to this RSS feed, copy and paste this URL into your RSS reader. Is it really in the format of your first string? Quote>I have this message error : error C2440: 'type cast' : Quote>cannot convert from 'CString' to 'char *'. If you are looking for a way to make your char array a C string, you should just add dta [len] = '\0'; after your while loop. The only reason I can come up with for you not being able to cast it is that you are compiling your application for unicode. the better question is: Is this worse than, More than likely this will never fail, as all it is doing is a, How to convert string to const unsigned char* without using reinterpret_cast (modern approach), Why on earth are people paying for digital real estate? If you want to use security functions, you should stick with well known and good tested libraries like openssl. Suppose if we have a string larger than MAX_LENGTH, then this method will fail to copy. For skilled one it could be matrer of several minutes only :/. You'd have to do this anyway, even for the next step. So, your code will work in both ANSI/MBCS and Unicode builds (Unicode build is the default build settingsince Visual C++ 2005). 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. 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. ur reply is also helpful to me! strcpy_s(g_sXPS8ServerAddress, numberOfElements, buf); Instead, if you want to code in a Unicode-neutral format (i.e. On the initialization of the const char *. Hi, I have written this code, and at the end, I am trying to write a vector of strings into a text file. Here, the idea is to pass the const char* returned by the string::c_str or string::data functions to the strcpy () function, which internally copies it into the specified character array and returns a pointer it. Convert a std::string to char* in C++ Unhandled exception at 0x1022f95b (msvcr80d.dll) in STXM_Control.exe: 0xC0000005: Access violation writing location 0x0064aed8. c++ - How to convert string to const unsigned char* without using Convert std::string to const char* in C++ | Techie Delight 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). We can call this function to get a const char* to the characters in the string. Please include an example string from the servers answer to the request. Seems more like a generic buffer.