1

I'm trying to convert a wchar_t array into an int array which contains the encoding of each wchar_t element in C. I know I can do this by a loop like the code below, is there any other way without using a loop which can greatly improve performance?

 for(int i=0; i< filesize; i++){
    t[i] = (int)p[i];   //t is an int array, p is a wchar_t array
}
  • 3
    you could use memcpy i guess – lulle2007200 May 09 '21 at 19:39
  • If int and wchar_t are compatible, you could get away with a memcpy, but probably the code gets compiled to a memcpy anyway in that case. So probably there's nothing that can be done, although I'd consider using the wchar_t array directly if possible. – Paul Hankin May 09 '21 at 19:42
  • @lulle how? can you provide an example code? – wevrqwevrq2 May 09 '21 at 19:46
  • @PaulHankin can you provide an example code using memcpy? yes, i would like to use wchar_t array directly in cuda which doesnt support, so i'am trying to turn it into int array first in device then convert it back in host – wevrqwevrq2 May 09 '21 at 19:49

2 Answers2

2

No. In that case there is no real alternative (at least if you have portability in mind). Otherwise mediocrevegetable1 is a possible solution.

1

Assuming wchar_t and int have the same size, memcpy is probably what you want.

#include <string.h>
#include <wchar.h>

int main(void)
{
    _Static_assert(sizeof (int) == sizeof (wchar_t), "This won't work");
    wchar_t warr[3] = {L'a', L'b', L'c'};
    int iarr[3] = {0};
    memcpy(iarr, warr, sizeof warr);
    // iarr now holds the same contents as warr
}
mediocrevegetable1
  • 4,086
  • 1
  • 11
  • 33
  • thanks for the answer, but i get this error when testing your code, what should i do?: test.cu(7): error: identifier "_Static_assert" is undefined – wevrqwevrq2 May 09 '21 at 20:09
  • @wevrqwevrq2 it seems that you're compiling your code as pre-C11. Either add a compiler option to choose C11 or higher (e.g. on GCC this is `-std=c11`) or include `` and replace that line with `assert(sizeof (int) == sizeof (wchar_t));`. [Example](https://godbolt.org/z/eEh9K37eE). – mediocrevegetable1 May 09 '21 at 20:18