locked
Little Endian to integer and vice versa RRS feed

  • Question

  • User-421523946 posted

    I have data that is is stored as little endian format and I need to convert it to an integer and convert an integer to a little endian.

    Has anyone got any good for doing this?

    I've done lots of trawling through Google but I'm just getting more and more confused!


    Thursday, January 21, 2010 10:47 AM

Answers

  • User-1110131619 posted

    I have some old C# code that was supposed to deal with converting Int32s from Host Byte Order to Network Byte Order to pass over a socket. The code has never been tested so even if it is wrong, it may give you some ideas. 

    The method that retrieves the Int32 from an array of bytes was written to be passed in the array and an index in the array that indicates where to read the Int32.  Here are the methods...hope they help...

     

    		public static Int32 RetrieveInt32FromBytes( byte[] bytes, ref int startIndex )
    		{
    			Int32 value = 0;
    			value = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(bytes, startIndex));
    			startIndex += 4;
    			return value;
    		}
    
    
    		public static byte[] RetrieveBytesFromInt32( Int32 value )
    		{
    			byte[] bytes;
    
    			bytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((Int32)value));
    
    			return bytes;
    		}


     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 21, 2010 12:02 PM

All replies

  • User-1110131619 posted

    I have some old C# code that was supposed to deal with converting Int32s from Host Byte Order to Network Byte Order to pass over a socket. The code has never been tested so even if it is wrong, it may give you some ideas. 

    The method that retrieves the Int32 from an array of bytes was written to be passed in the array and an index in the array that indicates where to read the Int32.  Here are the methods...hope they help...

     

    		public static Int32 RetrieveInt32FromBytes( byte[] bytes, ref int startIndex )
    		{
    			Int32 value = 0;
    			value = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(bytes, startIndex));
    			startIndex += 4;
    			return value;
    		}
    
    
    		public static byte[] RetrieveBytesFromInt32( Int32 value )
    		{
    			byte[] bytes;
    
    			bytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((Int32)value));
    
    			return bytes;
    		}


     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 21, 2010 12:02 PM
  • User-421523946 posted

    Thanks very much, I'll have a look at the code this morning :)

    Friday, January 22, 2010 2:51 AM