-1

I have two types and one function. One type is

char one[32]

The other type is

typedef union _DATA{
    UINT8 byte[32];
    INT8  iByte[32];
}DATA

The function gets DATA as input parameter,

void Compute(DATA data){}

Now, I have a char* (char[32]) type and I wish to convert it to DATA type and pass it as a parameter for Compute. Both types are 32Byte size, and I want a fast way to convert type.
I thought of memcpy,but it is slow since it copies the data.
Can I use pointer somehow to pass it char* as DATA type?

John Doyle
  • 898
  • 2
  • 9
  • 22
  • 5
    Unrelated to your question, but don't use leading underscore followed by an upper-case letter, such symbol names are [reserved by the "implementation" (compiler ad standard library) in all scopes](http://stackoverflow.com/q/228783/440558). Also, in C++ you don't need `typedef` for structures, classes or enumeration, a structure, class or enumeration tag can also be used as a type. – Some programmer dude Jun 29 '16 at 09:49
  • DATA d = * ((DATA *)one); – Colin Jun 29 '16 at 09:50
  • @Colin__s : theoretically, that's UB. On most architectures, it'll just work (tm). – lorro Jun 29 '16 at 09:52
  • What is the real usage of the union here? I believe that there is a underlying general design problem. – Klaus Jun 29 '16 at 09:58
  • @Colin__s Thanks! I Think this might work – John Doyle Jun 29 '16 at 09:58
  • @Klaus yes.. I agree.. I don't know why union is there.. but the code is not mine and this is unchangeable so.. – John Doyle Jun 29 '16 at 10:00
  • Just be aware as lorro said, it is undefined behavior. All depends on where the char array is, and whether you can do unaligned reads. – Colin Jun 29 '16 at 10:01
  • If you worry so much about copying, why is the union passed *by value* to the function? That will copy the data anyway. – Some programmer dude Jun 29 '16 at 10:01
  • @JoachimPileborg You are right. But the function is not made by me, and I wish to minimize the copy before passing it to function. Otherwise there are two copies so – John Doyle Jun 29 '16 at 10:03

1 Answers1

1

The only way of doing it without breaking strict aliasing and being well-defined is to copy from the character array into the correct array of the union.

Perhaps something like

DATA data;
if (std::is_signed<char>::value)
{
    std::copy_n(one, 32, data.iByte);
}
else
{
    std::copy_n(one, 32, data.byte);
}

And no it's not going to be "slow", unless you do this thousands of time per second. Measure and profile first, don't fall into the trap of premature optimization.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621