Extract a long from a byte array. - CSharp System

CSharp examples for System:Byte Array

Description

Extract a long from a byte array.

Demo Code

/// Distributed under the Mozilla Public License                            *
using System;//from   w  w  w  . java 2 s  . c o  m

public class Main{
        //FIXME: this routine is broken in the sense that it performs
        //       implicit byte order conversion
        /// <summary> Extract a long from a byte array.
        /// 
        /// </summary>
        /// <param name="bytes">an array.
        /// </param>
        /// <param name="pos">the starting position where the integer is stored.
        /// </param>
        /// <param name="cnt">the number of bytes which contain the integer.
        /// </param>
        /// <returns> the long, or <b>0</b> if the index/length to use 
        /// would cause an ArrayOutOfBoundsException
        /// </returns>
        public static long extractLong(byte[] bytes, int pos, int cnt)
        {
            // commented out because it seems like it might mask a fundamental 
            // problem, if the caller is referencing positions out of bounds and 
            // silently getting back '0'.
            //   if((pos + cnt) > bytes.length) return 0;
            long value_Renamed = 0;
            for (int i = 0; i < cnt; i++)
                value_Renamed |= ((bytes[pos + cnt - i - 1] & 0xffL) << 8 * i);
            
            return value_Renamed;
        }
}

Related Tutorials