Byte[] to UInt[]

Joined
Nov 6, 2010
Messages
1,561
Reaction score
394
I have the following code to convert a 16-byte array to a uint32 array with 4 values.

Code:
                Console.Write("DATA: ");
                String dataStr = Console.ReadLine();
                
                Console.Write("KEY: ");
                String keyStr = Console.ReadLine();

                byte[] keyBytes = new byte[16];
                keyBytes = Encoding.ASCII.GetBytes(keyStr);

                foreach(byte element in keyBytes)
                {
                     if (i < 4)
                     {
                         uint uKey = Convert.ToUInt32(element);
                         uKeyArray[i] = uKey;
                         i++;
                     }
                 }

Simple enough right? If that were the correct code, sure..


This is the array I'll get, converting like this:
Code:
0x00000066 0x0000006f 0x0000006f 0x00000062

It gives me, indeed, 4 uint32s.

but I need THIS to be the output:
Code:
0x666f6f62 0x61720000 0x00000000 0x00000000

This is what the byte array looks like, before anything happens:

Code:
66 6f 6f 62 - 61 72 00 00 - 00 00 00 00 - 00 00 00 00

How do I get the desired output? :(
 
You're using C#, not C++.

Code:
using System.Linq;

Code:
byte[] data = new byte[16]; // in reality, should be your actual values
IEnumerable<uint> values = Enumerable.Range(0, data.Length / 4)
                                     .Select(n => BitConverter.ToUInt32(data, n * 4))
          
foreach(uint num in values) 
     Console.WriteLine(num);
 
I am not sure what you wanted, so i did both options (See option 1 and Option 2), Option 1 as well as Option 2 could be optimized in speed, however that requires "complicated" code. (It is harder to understand.)

Code:
        private static readonly byte[] mBytes = { 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };


        public static void Main(string[] args)
        {


            uint[] mRet = new uint[4]; //16 bytes / devided by the size of a uint(4) = 16/4 = 4


            //IDK what you mean, but relise that 0x666f6f62 is not the uint represented by { 0x66, 0x6f, 0x6f, 0x62 } 
            Console.WriteLine(BitConverter.ToUInt32(mBytes, 0).ToString("X")); //Option 1
            Console.WriteLine(0x666f6f62.ToString("X"));  //Option 2 




            //Option 1


            for (int i = 0; i < 16; i += 4) 
            {
                mRet[i / 4] = BitConverter.ToUInt32(mBytes, i);
            }


            Console.Write("[Options 1]::");
            foreach (var u in mRet)
            {
                Console.Write(u.ToString("X") + "-");
            }
            Console.WriteLine();
           
           
            //Option 2


            for (int i = 0; i < 16; i += 4)
            {
                //StringBuilder would be better
                mRet[i / 4] = uint.Parse(mBytes[i].ToString("X") + mBytes[i + 1].ToString("X") + mBytes[i + 2].ToString("X") + mBytes[i + 3].ToString("X"), System.Globalization.NumberStyles.HexNumber);           
            }


            Console.Write("[Option 2]::");


            foreach (var u in mRet)
            {
                Console.Write(u.ToString("X") + "-");
            }


            Console.ReadLine();


           


        }
 
Last edited:
I am not sure what you wanted, so i did both options (See option 1 and Option 2), Option 1 as well as Option 2 could be optimized in speed, however that requires "complicated" code. (It is harder to understand.)

oh my... how did you even come up with something this random and complicated?
 
oh my... how did you even come up with something this random and complicated?

I made it easier for you ....:marchmellow:
Code:
 private static readonly byte[] mBytes = { 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };


        public static void Main(string[] args)
        {


            uint[] mRet = new uint[4];
 Buffer.BlockCopy(mBytes, 0, mRet, 0, mBytes.Length);
}
 
The second option looks slower...

The second options has nothing to do with the first options,

The first option is to simply convert the 4 bytes to its uint representing value.
in this case the array: {0x66, 0x6f, 0x6f, 0x62 } will be converted to the uint :0x626F66, this could be done with a for loop,buffer.blockcopy,bit shifting,pointers etc

While the second option is to convert the HexNumber of those 4 bytes to its uint representing value.
In this case the array: { 0x66, 0x6f, 0x6f, 0x62 } will be converted to the uint: 0x666F6F62,this requires you to first get the hex string and so the second option could be speed up with using something like this:

Code:
[COLOR=#00008B]public [/COLOR][COLOR=#00008B]static [/COLOR][COLOR=#00008B]string[/COLOR][COLOR=#2B91AF]ToHex[/COLOR][COLOR=#000000]([/COLOR][COLOR=#00008B]this [/COLOR][COLOR=#00008B]byte[/COLOR][COLOR=#000000][][/COLOR][COLOR=#000000] bytes[/COLOR][COLOR=#000000]) //by [/COLOR][URL="http://stackoverflow.com/users/21784/kgriffs"]kgriffs[/URL][COLOR=#000000]
[/COLOR][COLOR=#000000]{[/COLOR][COLOR=#000000]
    [/COLOR][COLOR=#00008B]char[/COLOR][COLOR=#000000][][/COLOR][COLOR=#000000] c [/COLOR][COLOR=#000000]=[/COLOR][COLOR=#00008B]new [/COLOR][COLOR=#00008B]char[/COLOR][COLOR=#000000][[/COLOR][COLOR=#000000]bytes[/COLOR][COLOR=#000000].[/COLOR][COLOR=#2B91AF]Length[/COLOR][COLOR=#000000]*[/COLOR][COLOR=#800000]2[/COLOR][COLOR=#000000]];[/COLOR][COLOR=#000000]

    [/COLOR][COLOR=#00008B]byte[/COLOR][COLOR=#000000] b[/COLOR][COLOR=#000000];[/COLOR][COLOR=#000000]

    [/COLOR][COLOR=#00008B]for[/COLOR][COLOR=#000000]([/COLOR][COLOR=#2B91AF]int[/COLOR][COLOR=#000000] bx [/COLOR][COLOR=#000000]=[/COLOR][COLOR=#800000]0[/COLOR][COLOR=#000000],[/COLOR][COLOR=#000000] cx [/COLOR][COLOR=#000000]=[/COLOR][COLOR=#800000]0[/COLOR][COLOR=#000000];[/COLOR][COLOR=#000000] bx [/COLOR][COLOR=#000000]<[/COLOR][COLOR=#000000] bytes[/COLOR][COLOR=#000000].[/COLOR][COLOR=#2B91AF]Length[/COLOR][COLOR=#000000];[/COLOR][COLOR=#000000]++[/COLOR][COLOR=#000000]bx[/COLOR][COLOR=#000000],[/COLOR][COLOR=#000000]++[/COLOR][COLOR=#000000]cx[/COLOR][COLOR=#000000])[/COLOR][COLOR=#000000] 
    [/COLOR][COLOR=#000000]{[/COLOR][COLOR=#000000]
        b [/COLOR][COLOR=#000000]=[/COLOR][COLOR=#000000](([/COLOR][COLOR=#00008B]byte[/COLOR][COLOR=#000000])([/COLOR][COLOR=#000000]bytes[/COLOR][COLOR=#000000][[/COLOR][COLOR=#000000]bx[/COLOR][COLOR=#000000]][/COLOR][COLOR=#000000]>>[/COLOR][COLOR=#800000]4[/COLOR][COLOR=#000000]));[/COLOR][COLOR=#000000]
        c[/COLOR][COLOR=#000000][[/COLOR][COLOR=#000000]cx[/COLOR][COLOR=#000000]][/COLOR][COLOR=#000000]=[/COLOR][COLOR=#000000]([/COLOR][COLOR=#00008B]char[/COLOR][COLOR=#000000])([/COLOR][COLOR=#000000]b [/COLOR][COLOR=#000000]>[/COLOR][COLOR=#800000]9[/COLOR][COLOR=#000000]?[/COLOR][COLOR=#000000] b [/COLOR][COLOR=#000000]+[/COLOR][COLOR=#800000]0x37[/COLOR][COLOR=#000000]+[/COLOR][COLOR=#800000]0x20[/COLOR][COLOR=#000000]:[/COLOR][COLOR=#000000] b [/COLOR][COLOR=#000000]+[/COLOR][COLOR=#800000]0x30[/COLOR][COLOR=#000000]);[/COLOR][COLOR=#000000]

        b [/COLOR][COLOR=#000000]=[/COLOR][COLOR=#000000](([/COLOR][COLOR=#00008B]byte[/COLOR][COLOR=#000000])([/COLOR][COLOR=#000000]bytes[/COLOR][COLOR=#000000][[/COLOR][COLOR=#000000]bx[/COLOR][COLOR=#000000]][/COLOR][COLOR=#000000]&[/COLOR][COLOR=#800000]0x0F[/COLOR][COLOR=#000000]));[/COLOR][COLOR=#000000]
        c[/COLOR][COLOR=#000000][++[/COLOR][COLOR=#000000]cx[/COLOR][COLOR=#000000]]=([/COLOR][COLOR=#00008B]char[/COLOR][COLOR=#000000])([/COLOR][COLOR=#000000]b [/COLOR][COLOR=#000000]>[/COLOR][COLOR=#800000]9[/COLOR][COLOR=#000000]?[/COLOR][COLOR=#000000] b [/COLOR][COLOR=#000000]+[/COLOR][COLOR=#800000]0x37[/COLOR][COLOR=#000000]+[/COLOR][COLOR=#800000]0x20[/COLOR][COLOR=#000000]:[/COLOR][COLOR=#000000] b [/COLOR][COLOR=#000000]+[/COLOR][COLOR=#800000]0x30[/COLOR][COLOR=#000000]);[/COLOR][COLOR=#000000]
    [/COLOR][COLOR=#000000]}[/COLOR][COLOR=#000000]

    [/COLOR][COLOR=#00008B]return [/COLOR][COLOR=#00008B]new [/COLOR][COLOR=#00008B]string[/COLOR][COLOR=#000000]([/COLOR][COLOR=#000000]c[/COLOR][COLOR=#000000]);[/COLOR][COLOR=#000000]
[/COLOR][COLOR=#000000]}[/COLOR]

 
Last edited:
Yeah..all of that is wrong. I Feel I was clear enough, TimeBomb lol

Tired of the question "y u do this". I have my reasons. I'm implementing that shitty also XTEA for a Shoutcast broadcaster.

I think I figured it out tho. I'll just convert the bytes to string representation ("6f6f" etc) then push them together, then convert THAT string[] to a uint32[]

It's a cheap workaround but if I'm already using an algorithm like XTEA, perfectionism is pissing in the wind.
 
The second options has nothing to do with the first options,

The first option is to simply convert the 4 bytes to its uint representing value.
in this case the array: {0x66, 0x6f, 0x6f, 0x62 } will be converted to the uint :0x626F66, this could be done with a for loop,buffer.blockcopy,bit shifting,pointers etc

While the second option is to convert the HexNumber of those 4 bytes to its uint representing value.
In this case the array: { 0x66, 0x6f, 0x6f, 0x62 } will be converted to the uint: 0x666F6F62,this requires you to first get the hex string and so the second option could be speed up with using something like this:

Code:
[COLOR=#00008B]public [/COLOR][COLOR=#00008B]static [/COLOR][COLOR=#00008B]string[/COLOR][COLOR=#2B91AF]ToHex[/COLOR][COLOR=#000000]([/COLOR][COLOR=#00008B]this [/COLOR][COLOR=#00008B]byte[/COLOR][COLOR=#000000][][/COLOR][COLOR=#000000] bytes[/COLOR][COLOR=#000000]) //by [/COLOR][URL="http://stackoverflow.com/users/21784/kgriffs"]kgriffs[/URL][COLOR=#000000]
[/COLOR][COLOR=#000000]{[/COLOR][COLOR=#000000]
    [/COLOR][COLOR=#00008B]char[/COLOR][COLOR=#000000][][/COLOR][COLOR=#000000] c [/COLOR][COLOR=#000000]=[/COLOR][COLOR=#00008B]new [/COLOR][COLOR=#00008B]char[/COLOR][COLOR=#000000][[/COLOR][COLOR=#000000]bytes[/COLOR][COLOR=#000000].[/COLOR][COLOR=#2B91AF]Length[/COLOR][COLOR=#000000]*[/COLOR][COLOR=#800000]2[/COLOR][COLOR=#000000]];[/COLOR][COLOR=#000000]

    [/COLOR][COLOR=#00008B]byte[/COLOR][COLOR=#000000] b[/COLOR][COLOR=#000000];[/COLOR][COLOR=#000000]

    [/COLOR][COLOR=#00008B]for[/COLOR][COLOR=#000000]([/COLOR][COLOR=#2B91AF]int[/COLOR][COLOR=#000000] bx [/COLOR][COLOR=#000000]=[/COLOR][COLOR=#800000]0[/COLOR][COLOR=#000000],[/COLOR][COLOR=#000000] cx [/COLOR][COLOR=#000000]=[/COLOR][COLOR=#800000]0[/COLOR][COLOR=#000000];[/COLOR][COLOR=#000000] bx [/COLOR][COLOR=#000000]<[/COLOR][COLOR=#000000] bytes[/COLOR][COLOR=#000000].[/COLOR][COLOR=#2B91AF]Length[/COLOR][COLOR=#000000];[/COLOR][COLOR=#000000]++[/COLOR][COLOR=#000000]bx[/COLOR][COLOR=#000000],[/COLOR][COLOR=#000000]++[/COLOR][COLOR=#000000]cx[/COLOR][COLOR=#000000])[/COLOR][COLOR=#000000] 
    [/COLOR][COLOR=#000000]{[/COLOR][COLOR=#000000]
        b [/COLOR][COLOR=#000000]=[/COLOR][COLOR=#000000](([/COLOR][COLOR=#00008B]byte[/COLOR][COLOR=#000000])([/COLOR][COLOR=#000000]bytes[/COLOR][COLOR=#000000][[/COLOR][COLOR=#000000]bx[/COLOR][COLOR=#000000]][/COLOR][COLOR=#000000]>>[/COLOR][COLOR=#800000]4[/COLOR][COLOR=#000000]));[/COLOR][COLOR=#000000]
        c[/COLOR][COLOR=#000000][[/COLOR][COLOR=#000000]cx[/COLOR][COLOR=#000000]][/COLOR][COLOR=#000000]=[/COLOR][COLOR=#000000]([/COLOR][COLOR=#00008B]char[/COLOR][COLOR=#000000])([/COLOR][COLOR=#000000]b [/COLOR][COLOR=#000000]>[/COLOR][COLOR=#800000]9[/COLOR][COLOR=#000000]?[/COLOR][COLOR=#000000] b [/COLOR][COLOR=#000000]+[/COLOR][COLOR=#800000]0x37[/COLOR][COLOR=#000000]+[/COLOR][COLOR=#800000]0x20[/COLOR][COLOR=#000000]:[/COLOR][COLOR=#000000] b [/COLOR][COLOR=#000000]+[/COLOR][COLOR=#800000]0x30[/COLOR][COLOR=#000000]);[/COLOR][COLOR=#000000]

        b [/COLOR][COLOR=#000000]=[/COLOR][COLOR=#000000](([/COLOR][COLOR=#00008B]byte[/COLOR][COLOR=#000000])([/COLOR][COLOR=#000000]bytes[/COLOR][COLOR=#000000][[/COLOR][COLOR=#000000]bx[/COLOR][COLOR=#000000]][/COLOR][COLOR=#000000]&[/COLOR][COLOR=#800000]0x0F[/COLOR][COLOR=#000000]));[/COLOR][COLOR=#000000]
        c[/COLOR][COLOR=#000000][++[/COLOR][COLOR=#000000]cx[/COLOR][COLOR=#000000]]=([/COLOR][COLOR=#00008B]char[/COLOR][COLOR=#000000])([/COLOR][COLOR=#000000]b [/COLOR][COLOR=#000000]>[/COLOR][COLOR=#800000]9[/COLOR][COLOR=#000000]?[/COLOR][COLOR=#000000] b [/COLOR][COLOR=#000000]+[/COLOR][COLOR=#800000]0x37[/COLOR][COLOR=#000000]+[/COLOR][COLOR=#800000]0x20[/COLOR][COLOR=#000000]:[/COLOR][COLOR=#000000] b [/COLOR][COLOR=#000000]+[/COLOR][COLOR=#800000]0x30[/COLOR][COLOR=#000000]);[/COLOR][COLOR=#000000]
    [/COLOR][COLOR=#000000]}[/COLOR][COLOR=#000000]

    [/COLOR][COLOR=#00008B]return [/COLOR][COLOR=#00008B]new [/COLOR][COLOR=#00008B]string[/COLOR][COLOR=#000000]([/COLOR][COLOR=#000000]c[/COLOR][COLOR=#000000]);[/COLOR][COLOR=#000000]
[/COLOR][COLOR=#000000]}[/COLOR]


Is calling BitConverter.ToString(bytes) too mainstream for you? wtf?
 
Is calling BitConverter.ToString(bytes) too mainstream for you? wtf?

BitConverter.ToString(bytes) is a very expensive* method. If this is called to often it could cause a serious performance lose. You can see the impact if you run the code below. BitConverter will be even more slower if you add the ".replace("-","")".

Code:
   private const int Times = 1000000;
        private const int Size = 1024;
        private static byte[] mValues = new byte[Size];




        public static void Main(string[] args)
        {
            for (int i = 0; i < Size; i++)
            {
                mValues[i] = (byte)i;
            }


            var s = new Stopwatch();
            s.Start();

            for (int i = 0; i < Times; i++)
            {
                var a = BitConverter.ToString(mValues);
            }


            s.Stop();
            Console.WriteLine("BitConverter->TotalTime::{0}   AVG::{1}", s.Elapsed, TimeSpan.FromTicks(s.Elapsed.Ticks / Times));


            s.Reset();

            s.Start();
            for (int i = 0; i < Times; i++)
            {
                var a = ToHex(mValues);
            }
            s.Stop();
            Console.WriteLine("ToHex->TotalTime::{0}   AVG::{1}", s.Elapsed, TimeSpan.FromTicks(s.Elapsed.Ticks / Times));
            Console.ReadLine();                   

        }


        public static string ToHex(byte[] bytes) 
        {
            char[] c = new char[bytes.Length * 2];

            byte b;

            for (int bx = 0, cx = 0; bx < bytes.Length; ++bx,++cx)
            {
                b = ((byte)(bytes[bx] >> 4));
                c[cx] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);


                b = ((byte)(bytes[bx] & 0x0F));
                c[++cx] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);
            }


            return new string(c);
        }
 
Last edited:
BitConverter.ToString(bytes) is a very expensive* method. If this is called to often it could cause a serious performance lose. You can see the impact if you run the code below. BitConverter will be even more slower if you add the ".replace("-","")".

I ran your code on an online C# compiler and got 40microseconds to 20microseconds.... Have you ever heard of premature optimization?
 
I ran your code on an online C# compiler and got 40microseconds to 20microseconds.... Have you ever heard of premature optimization?

I am at 80 (79.7) micro for bitcoverter against 18 (17.7) for to hex,with mono 3.12 , at a shitty pc out of 2007, now if you only have to call this method once , then i agree, but what if you have to call this method in some code critical section,or some kind encryption algorithm,now assume you use this algorithm to encrypt a couple of thousands files with all the size of 1 mb,or just a couple of files with a size of 1 GB,do you realy want to wait 2-4 times as long as needed?
 
Last edited:
@FullmetalPride this is the method you're looking for (source code):

sN6hDcV - Byte[] to UInt[] - RaGEZONE Forums


The following assumptions are made:

  • the length of the bytes array is equal to the length of the unsigned 32-bit integer array divided by 4, and
  • every subset of 4 elements in the bytes array is ordered from MSB to LSB.
 
Last edited:
FullmetalPride this is the method you're looking for (source code):

sN6hDcV - Byte[] to UInt[] - RaGEZONE Forums


The following assumptions are made:

  • the length of the bytes array is equal to the length of the unsigned 32-bit integer array divided by 4, and
  • every subset of 4 elements in the bytes array is ordered from MSB to LSB.

Actually, it's this:

Code:
            for (int i = 0; i < dataArr.Length; i++)
            {
                if (BitConverter.IsLittleEndian)
                {
                    // This ensures that the bytes are read correctly on little endian machines.
                    Array.Reverse(dataBytes, i * 4, 4);
                }
                /* This for loop runs through our array and converts each byte to uint32,
                 * Since every uint32 is four bytes, the index that bitConverter is going
                 * to start reading for the next uint is i * 4. 
                 */
                dataArr[i] = BitConverter.ToUInt32(dataBytes, i * 4);
            }

But thank you all very much :)
 
Back