Question

Add/Convert Char[] to wchar[]

Asked by: sandip132

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
}

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-04-14 at 05:56:04ID24320223
Tags

Add Convert Char[] to wchar[]

Topic

C++ Programming Language

Participating Experts
4
Points
250
Comments
26

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. CHAR * to WCHAR
    I have the following piece of code: void *body = "testcode"; wchar_t *d_Body = SysAllocStringLen(NULL,255); MultiByteToWideChar(CP_ACP,NULL,body,sizeof(body),d_Body,sizeof(d_Body)); But when I convert d_Body again to char * and print its value to file,the valu...
  2. char* to WCHAR*
    I'm attempting to use the MS speech SDK and in order to make this functional, I need to convert a null terminated char* (containing the text to say) to WCHAR* so that it may be plugged into Voice->Speak. I tried MultiByteToWideChar to no avail, perhaps due to a simple mist...
  3. The conversion from char string to a wchar array: is it ne…
    Hi, I wanted to do a strncmp() between 2 strings The problem is one argument is unsigned char *string and the other is a wide char array. I wanted to know what is a good solution in this case. Do I need to use mbstowcs/mbsnrtowcs to convert the char string to a wide char...
  4. convert wchar_t* to char*
    I have a function that returns a wchar_t* and need to convert this to a char* to use as an argument to another function. Any help appreciated.
  5. Convert char to wchar_t
    I'm using a function (part of mysql C api) which returns a char*, but I need a wchar_t*. What is the best way to convert this?

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: abelPosted on 2009-04-14 at 06:11:09ID: 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'
 
//

                                              
1:
2:
3:
4:
5:
6:

Select allOpen in new window

 

by: abelPosted on 2009-04-14 at 06:19:09ID: 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];
}  

                                              
1:
2:
3:
4:
5:
6:
7:

Select allOpen in new window

 

by: evilrixPosted on 2009-04-14 at 06:53:09ID: 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.

 

by: dolomitiPosted on 2009-04-14 at 07:02:53ID: 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

 

by: evilrixPosted on 2009-04-14 at 07:36:58ID: 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.

 

by: evilrixPosted on 2009-04-14 at 07:38:01ID: 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]  :)

 

by: sandip132Posted on 2009-04-14 at 07:47:36ID: 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.

 

by: evilrixPosted on 2009-04-14 at 07:56:22ID: 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.

 

by: dolomitiPosted on 2009-04-14 at 07:59:41ID: 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


 

by: evilrixPosted on 2009-04-14 at 08:03:15ID: 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.

 

by: dolomitiPosted on 2009-04-14 at 08:11:05ID: 24139138

there is no substantial diffenence
no between a function and another
but between what you and me are saying

 

by: evilrixPosted on 2009-04-14 at 08:12:03ID: 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;
	}
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:

Select allOpen in new window

 

by: evilrixPosted on 2009-04-14 at 08:14:58ID: 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.

 

by: DanRollinsPosted on 2009-04-14 at 15:09:06ID: 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;

 

by: sandip132Posted on 2009-04-14 at 18:45:16ID: 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.

 

by: DanRollinsPosted on 2009-04-14 at 19:25:50ID: 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?

 

by: sandip132Posted on 2009-04-14 at 19:53:02ID: 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.

 

by: DanRollinsPosted on 2009-04-14 at 20:07:32ID: 24144462

Please answer my question.  :-)
Is that the way the data looks when you get it from the database?

 

by: sandip132Posted on 2009-04-14 at 20:23:42ID: 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.

 

by: sandip132Posted on 2009-04-14 at 20:48:24ID: 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++;
}

                                              
1:
2:
3:
4:
5:
6:

Select allOpen in new window

 

by: evilrixPosted on 2009-04-14 at 23:48:49ID: 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. :)

 

by: evilrixPosted on 2009-04-14 at 23:50:34ID: 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.

 

by: sandip132Posted on 2009-04-15 at 02:50:49ID: 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

 

by: sandip132Posted on 2009-04-15 at 02:54:07ID: 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.

 

by: evilrixPosted on 2009-04-15 at 03:04:36ID: 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?

 

by: sandip132Posted on 2009-04-19 at 23:16:01ID: 31569868

Thanks all.

Sorry for late closing.

Points given for helpful tips also.


20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...