04-06-2022 11:19 AM
Hello
I am able to convert a U16 array to String successfully, but unable to get the other way round. i.e. String to U16 conversion
The attached code works good for string length if its even number, but for odd length the U16 array created is incomplete
Kindly guide.
Solved! Go to Solution.
04-06-2022 12:22 PM - edited 04-06-2022 12:23 PM
Your array input translates to (in \code to show unprintable characters):
"HELLO\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00"
Your string input is HELLO (i.e. 5 characters.) Obviously not the same!
(If you have an odd number of characters, you also need to decide to pad or truncate)
04-06-2022 12:23 PM - edited 04-06-2022 12:26 PM
@vihang wrote:
The attached code works good for string length if its even number, but for odd length the U16 array created is incomplete
So you need to detect if there are an odd number of characters in the string. If there is, append a NULL character (0x00).
I would also recommend using the Flatten To String and Unflatten From String to convert the data. There are inputs for the Endianess that you can set to "little-endian" and therefore avoid the need for "swap bytes".
04-06-2022 12:25 PM
If you are using a U16 for a string, each array entry is going to represent 2 characters. Since "HELLO" is an odd number of characters it seems like the swap bytes doesn't know what to do with only half of a U16 and doesn't return any data (which seems a bit odd to me). Any even length string seems to work in your example.
Anyway you need a way to make sure you have enough data to create a U16. The attached works, but I'm sure there are other ways that may be better to do this.
04-06-2022 12:34 PM
I would recommend "(un)flatten from/to string". It can include the endian conversion and even gives you a rudimentary error if things go wrong:
04-06-2022 08:34 PM
This is all you need:
04-07-2022 02:27 AM
Thanks
This worked for me
04-07-2022 02:29 AM
Thanks
This is superb!!!
04-07-2022 10:34 AM - edited 04-07-2022 10:49 AM
@vihang wrote:
Thanks
This worked for me
To pad to the next higher even size, you don't need any case structures.
Here's what I would do (note that bitwise operations are cheaper that Q&R, for example):