Click here to Skip to main content
15,885,792 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hello , pelase help me , i have a byte array b=new byte[4]{0,0,0,55}

i want output this as 00 37 00 00

i tried using
C#
if(BitConverter.IsLittleEndian)
    { b= Array.Reverse(b); }


and
C#
Array.Reverse(bytes, 0, bytes.Length);

    // to display
    BitConverter.ToString(b);


am getting output as 00 00 00 37 or 37 00 00 00

thanks
Posted
Comments
Thomas Daniels 5-Dec-14 8:58am    
You talk about reversing the array, but the 55 becomes 37. Is that intentional?
Fredrik Bornander 5-Dec-14 9:02am    
BitConverter.ToString will dump the values in hexadecimal format.
Thomas Daniels 5-Dec-14 9:06am    
Oh, I see. I missed that it was hex format.

1 solution

You need to look at the content of the 32bit data as two sets of 16bit datums.

Something like this might work for you;

C#
using System;

namespace BitStuff {
    class Program {

        static void Swap(ref byte a, ref byte b) {
            var temp = a;
            a = b;
            b = temp;
        }

        static byte[] FlipInt16(byte[] rawData) {
            for (var i = 0; i < rawData.Length; i += 2) // Step two for 2x8 bits=16
                Swap(ref rawData[i], ref rawData[i + 1]);
            return rawData;
        }

        static byte[] FlipInt32(byte[] rawData) {
            for (var i = 0; i < rawData.Length; i += 4)  {// Step four for 4x8 bits=32
                Swap(ref rawData[i + 0], ref rawData[i + 2]);
                Swap(ref rawData[i + 1], ref rawData[i + 3]);
            }
            return rawData;
        }

        static void Main(string[] args) {
            var b = new byte[] { 0, 0, 0, 55 };
            Console.WriteLine("Original: {0}", BitConverter.ToString(b));
            if (BitConverter.IsLittleEndian) {
                FlipInt32(b);
            }
            Console.WriteLine("Adjusted: {0}", BitConverter.ToString(b));
        }
    }
}



Hope this helps,
Fredrik
 
Share this answer
 
v2
Comments
GagKumar 5-Dec-14 9:09am    
Hi thanks for response, i am looking output as 00 37 00 00, its good job
Fredrik Bornander 5-Dec-14 9:10am    
Then flip the lower 16 bits with the upper 16 bits as well, the process is the same.
GagKumar 5-Dec-14 9:31am    
sorry to ask you again Fredrik,

am getting point of you.
Fredrik Bornander 5-Dec-14 9:36am    
I updated the answer with a flip for 32bit.
GagKumar 5-Dec-14 9:35am    
go it ,thanks

public static byte[] ReverseBytes(byte[] outArray)
{
byte temp;
int hitr = outArray.Length - 1;

for (int ctr = 0; ctr < outArray.Length / 2; ctr++)
{
temp = outArray[ctr];
outArray[ctr] = inArray[hitr];
outArray[hitr] = temp;
hitr -= 1;
}
return outArray;
}

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