Solved

Add/Convert Char[] to wchar[]

Posted on 2009-04-14
26
1,446 Views
Last Modified: 2012-05-06
I am getting char string like 0x30a2  0x30c6  0x30a3  0x30d3  0x30c6 in below for loop.

I want to add these string one by one in into the wchar_t array.

like this :
SASI_DATAWCHR[0] = 0x30a2  
SASI_DATAWCHR[1] = 0x30c6  
SASI_DATAWCHR[2] = 0x30a3  
SASI_DATAWCHR[3] = 0x30d3  
SASI_DATAWCHR[4] = 0x30c6
:
:
:
Tried mbstowcs, but copying some different value into array.

Is there any other way?

Thanks in advance.
char outStr[6];

wchar_t SASI_DATAWCHR[1000]; 

int intCnter=0;
 

for (wstring::iterator i = SASI_DATAW.begin(); i != SASI_DATAW.end(); ++i) { 

	sprintf(outStr,"0x%x",(int) *i);

	SASI_DATAWCHR[intCnter]=(wchar_t)outStr;   // << Not adding actual values.

	intCnter++;

       //mbstowcs((wchar_t*)SASI_DATAWCHR[intCnter],outStr[0],10)  // NOT WORKING

}

Open in new window

0
Comment
Question by:sandip132
  • 10
  • 8
  • 3
  • +2
26 Comments
 
LVL 39

Assisted Solution

by:abel
abel earned 25 total points
ID: 24137727
Isn't a simple case what you need? This works for me:

// from wchar_t to char
 

char c = 'D';

wchar_t wc = (wchar_t) c;   // now contains L'D'
 

//

Open in new window

0
 
LVL 39

Expert Comment

by:abel
ID: 24137798
can you show the declaration of SASI_DATAW?

It looks to me that you want to enter a pointer to the char array, or do you mean to copy the actual values one by one? There are six of them, this works for me:


char outStr[6] = {'a', 'b', 'e', 'l', '2', '0'};

wchar_t SASI_DATAWCHR[1000]; 
 

for(int i = 0; i < 6; i++)

{   

    SASI_DATAWCHR[i]=(wchar_t) outStr[i];

}  

Open in new window

0
 
LVL 40

Assisted Solution

by:evilrix
evilrix earned 175 total points
ID: 24138170
I'm a little confused. You are iterating through a wstring, which generally has a value_type of wchar_t and the array you are looking to populate also has a element type of wchar_t so where exactly does the char conversion come in? Why don't you just copy the string directly to the array using std::copy()?

http://www.sgi.com/tech/stl/copy.html

std::copy(SSDATAW.begin(), SSDATAW.end(), SASI_DATAWCHR);

Hint: Pointers can be used as iterators.

Regarding the idea of casting from char to wchar_t, it's not safe to do this because there is no guarantee that the char type directly maps to a wchar_t type of the same value. It all depends upon the character encoding. If it's simple ASCII then it'll probably work ok but if it's UTF8 encoded data (which is a multi-byte encoding) then this isn't going to work as expected.

The correct and safe way to convert a narrow to wide character and a wide to narrow narrow is to use mbtowc and wctomb respectively. The links below give full details on how to use these.

http://www.cplusplus.com/reference/clibrary/cstdlib/mbtowc/
http://www.cplusplus.com/reference/clibrary/cstdlib/wctomb/


If this doesn't help please explain why and we can take it from there.
0
 
LVL 7

Assisted Solution

by:dolomiti
dolomiti earned 25 total points
ID: 24138271
hi,
you cannot copy a printable rappresentation of a binary value (also if it represent a char)
to the binary variable:

char c=65
equivalent to
char c='A'

but not equal to

char c="A" that gives compilation error
neither c=(char)"A" that gives no error (maby), but means:
put address of automatic area "A" into a char: compiler takes low or high 8bits of pointer
"A" (2,4,8  bytes) and put in c var: difficulty it will be 65 seeing with debug.

It seems that use of mbstowcs
http://msdn.microsoft.com/en-us/library/k1f9b8cy(VS.80).aspx
is a little different.

bye
vic
0
 
LVL 40

Expert Comment

by:evilrix
ID: 24138715
>> char c="A" that gives compilation error
It will do "A" is not of type char but of type char const *.

>> It seems that use of mbstowcs
that is for converting strings and not chars... the asker wants to convert chars.
0
 
LVL 40

Expert Comment

by:evilrix
ID: 24138729
>> It will do "A" is not of type char but of type char const *.
Or, more correctly it is of type char const[2]  :)
0
 
LVL 12

Author Comment

by:sandip132
ID: 24138852
@abel:
>>wchar_t wc = (wchar_t) c;
doesnot convert the value as it is. It copies some integer value  and not 0x30a2 etc..  
SASI_DATAW is a wstring.
Please refer my expected output in my question.

@evilrix:
The char is to hold the Hex Unicode value of the characters in wstring. I need to convert it to Hex Unicode and then copy it in wchar_t array.
The both options mbtowc and wctomb not working. No function copies the actual data in wchar_t array.

@dolomiti:
tried your link too.

@All
I am doing this to pass the Hex Unicode wchar_t array to a third party API.

Upto this statement "sprintf(outStr,"0x%x",(int) *i);" everything works fine, I am getting the string in expected format, now I want to add these '0x30a2' chars in wchar_t array.
0
 
LVL 40

Accepted Solution

by:
evilrix earned 175 total points
ID: 24138971
>> The char is to hold the Hex Unicode value of the characters in wstring
Ok, I think you are getting yourself confused a little. What you are doing is converting the numeric value (for example) 0xFFEE to the string "0xFFEE". This is therefore a character array of 7 bytes (including the NULL terminator). You can then just store this in a wchar_t since that is a 16 bit (on Windows) data type, where as "0xFFEE" is a string. If you want to be storing the hex numeric value then just copy as I suggested above because putting 0xFFEE into a wchar_t as a numeric value is the same as copying a wchar_t holding that as a UTF16 char into another wchar_t. The bit pattern is the same because the values are the same. Does that make sense?

If you want the wchar_t value to be a string then you will need to copy 6 bytes (assuming a char is a byte) from outStr into the SASI_DATAWCHR array.

0
 
LVL 7

Expert Comment

by:dolomiti
ID: 24139001
hi,
probably competition, than collaboration, clouds posts interpretations.

me>>>It seems that use of mbstowcs ... is a little different
you>> that is for converting strings and not chars

I don't see a substantial difference in above sentences, different way to say the same thing

asker>>SASI_DATAWCHR[intCnter]=(wchar_t)outStr
me>>>char c="A"   as I wrote. is a no-sense in C

About this, I looked for another known way to present an incorrect operation


0
 
LVL 40

Expert Comment

by:evilrix
ID: 24139045
>> I don't see a substantial difference in above sentences, different way to say the same thing
They are completely different functions, with completely different prototypes that perform completely different tasks.
0
 
LVL 7

Expert Comment

by:dolomiti
ID: 24139138
there is no substantial diffenence
no between a function and another
but between what you and me are saying
0
 
LVL 40

Expert Comment

by:evilrix
ID: 24139158
I suspect you are trying to do something like below, although that might not be completely correct since I am still a bit fuzzy on what it is you're trying to achieve and why. It seems overly convoluted to me that you need to convert wide data into a string of hexadecimal so I'm not convinced this is what actually needs to be done.

So, how about we change this around a little. Rather than telling us what you are trying to do how about you explain your problem in terms of what you are trying to achieve. Tell us more about this 3rd party API. The function prototypes, describe the parameters, what format of data should be going in and what do they represent.
#include <string>

#include <sstream>
 

int main()

{

	char outStr[6] = {0};

	char SASI_DATAWCHR[1000] = {0}; 

	int intCnter=0;
 

	std::wstring SASI_DATAW = L"ABCD";
 

	size_t idx = 0;

	for (std::wstring::iterator i = SASI_DATAW.begin(); i != SASI_DATAW.end(); ++i)

	{

		sprintf(outStr,"0x%04x",(int) *i);

		memcpy(&SASI_DATAWCHR[idx], outStr, sizeof(char) * 6);

		idx += 6;

	}

}

Open in new window

0
 
LVL 40

Expert Comment

by:evilrix
ID: 24139192
@dolomiti, maybe there is just a language barrior problem here. I am guessing you are not a native English speaker, so maybe I misunderstood you, if so I am sorry. The point; however, is that if I have misunderstood then so too will the Asker (probably). I am just suggesting you make sure your posts are unambiguous so as not to confuse the issue and, thus, make life harder for both the asker and the other experts.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 49

Assisted Solution

by:DanRollins
DanRollins earned 25 total points
ID: 24143140
There is, indeed considerable confusion as to the desired output.
Based in an earliier question (http:CPP/Q_24312267.html), I suspect that you want the output to be a series of 6-byte 16-bit hex values, each separated by one comma and one space:
    "0x65ed, 0x8466, 0x82a6, 0x9bf5, 0x6893"
If so, then evilrix's last post will do as desired if you just ass the comma and the space:
    sprintf( outStr, "0x%04x, ", (int) *i );   // added comma space
    memcpy( &SASI_DATAWCHR[idx], outStr, sizeof(char) * 8 );  // changed 6 to 8
   idx  = 8;  // changed 6 to 8

Aslo, you will need to trim the final comma and space and apply the terminating NUL to the end when finished, like so:
   SASI_DATAWCHR[ idx - 2 ]= 0;
0
 
LVL 12

Author Comment

by:sandip132
ID: 24144180
I am Sorry. My question is confusing.

@evilrix:
Your example works fine, but its a char array. (char SASI_DATAWCHR[1000] = {0};)

@Dan,  evilrix, dolomiti,
I am getting Japanese character string from DB and I need to convert it into following formatted array .

The array I need to pass to the third party API is like below:

wchar_t txt2U[] = {0x30a2, 0x30c6, 0x30a3, 0x30d3, 0x30c6, 0x30a3, 0x30fb, 0x30ed, 0x30b0, 0x306b, 0x30b9, 0x30a2, 0x3055, 0x308c, 0x305f, 0x30a4, 0x0};



I have raised the points, after understanding the complexity of the question.
0
 
LVL 49

Expert Comment

by:DanRollins
ID: 24144354
I think I understand now, but just to be sure:
The data comes to you as a character string of text that looks like:
0x30a2  0x30c6  0x30a3  0x30d3
            ^^ --- two spaes?
That string is 32 bytes long. A set of 6 characters, two spaces, six more characters...
digit zero, letter ex, digit three, digit zero, letter aye, digit two, space, space, digit zero, letter ex, etc...
Is that correct?
0
 
LVL 12

Author Comment

by:sandip132
ID: 24144427
Dan,
Thank you very much for your response.  I am getting that data in char outStr[6] in each iteration of 'for' loop. I am afraid even if we concate it with " ," , it will be difficult to pass it as wchar_t array.

I found that it's unsafe to add the hex values in char.

Instead of adding SASI_DATAWCHR[intCnter]=(wchar_t)outStr;

is it safe to add
SASI_DATAWCHR[intCnter]=(int) *i);
directly?

I guess character representation of  (int) *i and "0x%x",(int) *i  would be same?


Let me give a try! Your suggestions are welcome.
0
 
LVL 49

Expert Comment

by:DanRollins
ID: 24144462
Please answer my question.  :-)
Is that the way the data looks when you get it from the database?
 
0
 
LVL 12

Author Comment

by:sandip132
ID: 24144516
Oops! Sorry for that, I misunderstood the question.

The input data that I get from database is pure Japanese characters, not in the form of 0x30a2...
I save it in wstring SASI_DATAW.

0
 
LVL 12

Author Comment

by:sandip132
ID: 24144579
ok! Here is what working.









wchar_t SASI_DATAWCHR[1000]; 

int intCnter=0;

for (wstring::iterator i = SASI_DATAW.begin(); i != SASI_DATAW.end(); ++i) { 

       SASI_DATAWCHR[intCnter]=(int) *i);

       intCnter++;

}

Open in new window

0
 
LVL 40

Assisted Solution

by:evilrix
evilrix earned 175 total points
ID: 24145265
>> The array I need to pass to the third party API is like below:

>> wchar_t txt2U[] = {0x30a2, 0x30c6, 0x30a3, 0x30d3, 0x30c6, 0x30a3, 0x30fb, 0x30ed, 0x30b0, 0x306b, 0x30b9, 0x30a2, 0x3055, 0x308c, 0x305f, 0x30a4, 0x0};

The example you've shown above is assigning each element of the wchar_t array with a NUMERIC hex value, which is 1 wide character. What you are describing as your requirement is to encode these hex values into their string format and then concatenate the strings into an array of a wide chars. I honestly think you are just getting yourself confused into thinking you need to code up something that isn't necessary because what you are describing makes little sense to me.

If this is the format of the data that the API needs that all you need to is this...

// Assuming it takes a null terminated string
void SomeApiFunc(wchar_t data[]); // Example prototype of API
SomeApiFunc(SASI_DATAW.str()); // Call the function

or maybe...

// Assuming it takes data and a length
void SomeApiFunc(wchar_t data[]), size_t len; // Example prototype of API
SomeApiFunc(SASI_DATAW.data(), SASI_DATAW.size()); // Call the function

Out of interest have you actually tried doing this? IF it works then great, if not I asked above for you to provide the prototype of the API function, can you do this please along with a description of the parameter because I think following the current train of thought is just creating confusion since we are (a) all guessing at what you're trying to do and (b) working on the premise that your understanding of the API is correct (please don't take offense to this comment as I don't mean it in a bad way).

>> Your example works fine, but its a char array. (char SASI_DATAWCHR[1000] = {0};)
It wasn't mean to be a solution, I was just trying to understand your problem better. :)
0
 
LVL 40

Expert Comment

by:evilrix
ID: 24145272
Incidentally, I see Dan has made an additional observation regarding the data format. I don't believe either of us can help you further without clear clarification of the data formats and the API prototyping, otherwise we're just guessing.
0
 
LVL 12

Author Comment

by:sandip132
ID: 24146184
evilrix,
Thanks for your honest efforts and sorry for the confusion again.

I assumed that, the format provided in Que :
SASI_DATAWCHR[0] = 0x30a2  
SASI_DATAWCHR[1] = 0x30c6  
SASI_DATAWCHR[2] = 0x30a3  
SASI_DATAWCHR[3] = 0x30d3  
SASI_DATAWCHR[4] = 0x30c6

And the other Array format :
wchar_t txt2U[] = {0x30a2, 0x30c6, 0x30a3, 0x30d3, 0x30c6, 0x30a3, 0x30fb, 0x30ed, 0x30b0, 0x306b, 0x30b9, 0x30a2, 0x3055, 0x308c, 0x305f, 0x30a4, 0x0};

are same. Instead of adding the elements at the time of initialization, my approach was to add the element one by one and pass that array to the API.

As I mentioned above the Third party API only takes the wchar_t array as parameter, there is really nothing to describe anything else.   APIFun(const wchar_t * text)

This is the final solution that I found working perfect for the problem.
http://www.experts-exchange.com/Programming/Languages/CPP/Q_24320223.html#a24144579
0
 
LVL 12

Author Comment

by:sandip132
ID: 24146203
>>You are iterating through a wstring, which generally has a value_type of wchar_t and the array you are looking to populate also has a element type of wchar_t so where exactly does the char conversion come in?

You was right. There is no need for any conversion into char.
0
 
LVL 40

Expert Comment

by:evilrix
ID: 24146253
>> I assumed that, the format provided in Que
Yes, your assumption is correct, both assign numeric hex values to the wchar_t elements.

>> This is the final solution
I'm happy we managed to find a working solution for you.

So, just one question from me... I just want to make sure that you understand why the proposed solution works. Obviously, it's nice that it does but my job would be incomplete if you don't understand why. Do you need further clarification or does it now make sense?
0
 
LVL 12

Author Closing Comment

by:sandip132
ID: 31569868
Thanks all.

Sorry for late closing.

Points given for helpful tips also.


0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now