Click here to Skip to main content
15,940,921 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a byte array.. Each index is having values like 0x01, 0x1D etc.. It can be seen that these values are 8 bit numbers. I want to convert them to 16 bit numbers.  for example, I want this type of result 0x0001 0x001D.  Is there some way to do this in C#?

What I have tried:

BitConverter class will be used. i want to get unsigned numbers. i am not sure which method will be used of BitConverter Class.
Updated 6-Jun-18 1:08am

There is no existing method as already noted in solution 1.

But it is quite simple to declare an array of ushort with the same number of items as in the byte array and copy the data within a loop:
ushort[] arr16 = new ushort[arr8.Length];
for (int i = 0; i < arr8.Length; i++)
    arr16[i] = arr8[i];
Share this answer
hamid18 6-Jun-18 9:12am    
thank you. it worked for me
Richard Deeming 6-Jun-18 9:17am    
You could simplify that slightly by using Array.ConvertAll[^]
ushort[] arr16 = Array.ConvertAll(arr8, b => (ushort)b);

However, for very large arrays, the performance impact of invoking the delegate for each item might become a problem.
Jochen Arndt 6-Jun-18 9:23am    
Thank you for sharing that. Have not looked for the Array conversion routines.

Don't you think that such a simple delegate is inlined resulting in similar - if not identical - generated code as my solution?
Jochen Arndt 6-Jun-18 9:39am    
Thank you again for the information.

I thought too much in the C++ direction where lambdas can be inlined by the compiler.
The BitConverter Class (System)[^] does not appear to have a method to do this for you. You will need to write your own.
Share this answer
hamid18 6-Jun-18 9:12am    

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900