Extract an integer from a byte array. - CSharp System

CSharp examples for System:Byte Array

Description

Extract an integer from a byte array.

Demo Code

/// Distributed under the Mozilla Public License                            *
using System;/*  w w  w  .ja v  a2s  .  c  o  m*/

public class Main{
        /// <summary> Extract an integer 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 integer, or <b>0</b> if the index/length to use 
        /// would cause an ArrayOutOfBoundsException
        /// </returns>
        public static int extractInteger(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;
            int value_Renamed = 0;
            for (int i = 0; i < cnt; i++)
                value_Renamed |= ((bytes[pos + cnt - i - 1] & 0xff) << 8 * i);
            
            return value_Renamed;
        }
}

Related Tutorials