2 //------------------------------------------------------------------------------
3 // <copyright file="BinHexEncoder.cs" company="Microsoft">
4 // Copyright (c) Microsoft Corporation. All rights reserved.
6 // <owner current="true" primary="true">Microsoft</owner>
7 //------------------------------------------------------------------------------
10 internal static partial class BinHexEncoder {
12 private const string s_hexDigits = "0123456789ABCDEF";
13 private const int CharsChunkSize = 128;
15 internal static void Encode( byte[] buffer, int index, int count, XmlWriter writer ) {
16 if ( buffer == null ) {
17 throw new ArgumentNullException( "buffer" );
20 throw new ArgumentOutOfRangeException( "index" );
23 throw new ArgumentOutOfRangeException( "count" );
25 if ( count > buffer.Length - index ) {
26 throw new ArgumentOutOfRangeException( "count" );
29 char[] chars = new char[ ( count * 2 ) < CharsChunkSize ? ( count * 2 ) : CharsChunkSize ];
30 int endIndex = index + count;
31 while ( index < endIndex ) {
32 int cnt = ( count < CharsChunkSize/2 ) ? count : CharsChunkSize/2;
33 int charCount = Encode( buffer, index, cnt, chars );
34 writer.WriteRaw( chars, 0, charCount );
40 internal static string Encode(byte[] inArray, int offsetIn, int count) {
41 if (null == inArray) {
42 throw new ArgumentNullException("inArray");
45 throw new ArgumentOutOfRangeException("offsetIn");
48 throw new ArgumentOutOfRangeException("count");
50 if (count > inArray.Length - offsetIn) {
51 throw new ArgumentOutOfRangeException("count");
54 char[] outArray = new char[2 * count];
55 int lenOut = Encode(inArray, offsetIn, count, outArray);
56 return new String(outArray, 0, lenOut);
59 private static int Encode(byte[] inArray, int offsetIn, int count, char[] outArray) {
60 int curOffsetOut =0, offsetOut = 0;
62 int lengthOut = outArray.Length;
64 for (int j=0; j<count; j++) {
65 b = inArray[offsetIn ++];
66 outArray[curOffsetOut ++] = s_hexDigits[b >> 4];
67 if (curOffsetOut == lengthOut) {
70 outArray[curOffsetOut ++] = s_hexDigits[b & 0xF];
71 if (curOffsetOut == lengthOut) {
75 return curOffsetOut - offsetOut;