Reputation: 5
how can I put a INT type variable to a wchar array ?
Thanks
EDIT:
Sorry for the short question. Yes we can cast INT to a WCHAR array using WCHAR*, but when we are retrieving back the result (WCHAR[] to INT), I just realize that we need to read size of 2 from WCHAR array since INT is 4 BYTEs which is equal to 2 WCHARs.
WCHAR arData[20];
INT iVal = 0;
wmemcpy((WCHAR*)&iVal, arData, (sizeof(INT))/2);
Is this the safest way to retrieve back INT value from WCHAR array
Upvotes: 0
Views: 1706
Reputation: 41852
WCHAR t[100];
int x = 3;
*((int *)t) = x;
or, if you want the text:
assuming your application is unicode, use wsprintf
WCHAR t[100];
int x = 3;
wsprintf(t, "%d", &x);
Upvotes: 1
Reputation: 84892
Technically, the way you do it is unsafe due to strict aliasing and alignment. The safest and the most portable way would be to read chars one by one and combine them with bit shifts.
While your code would work on a Windows PC, don't expect it to be portable or work for all compilers and compiler settings.
Basic example (can be improved to be more portable with regard to integer sizes, byte order, etc):
WCHAR arData[20];
...
// Read little-endian 32-bit integer from two 16-bit chars:
INT iVal = arData[0] | arData[1] << 16;
Upvotes: 1
Reputation: 5522
If you want to simply assign an int into a wchar array, use casting:
wchar wArray[N];
int num = xxx;
wArray[0] = (wchar)num;
If you want to insert the string value of the number, you need to use a conversion function like itoa().
Upvotes: 1