BinHexEncoder.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. //------------------------------------------------------------------------------
  2. // <copyright file="BinHexEncoder.cs" company="Microsoft">
  3. // Copyright (c) Microsoft Corporation. All rights reserved.
  4. // </copyright>
  5. // <owner current="true" primary="true">Microsoft</owner>
  6. //------------------------------------------------------------------------------
  7. namespace System.Xml {
  8. internal static partial class BinHexEncoder {
  9. private const string s_hexDigits = "0123456789ABCDEF";
  10. private const int CharsChunkSize = 128;
  11. internal static void Encode( byte[] buffer, int index, int count, XmlWriter writer ) {
  12. if ( buffer == null ) {
  13. throw new ArgumentNullException( "buffer" );
  14. }
  15. if ( index < 0 ) {
  16. throw new ArgumentOutOfRangeException( "index" );
  17. }
  18. if ( count < 0 ) {
  19. throw new ArgumentOutOfRangeException( "count" );
  20. }
  21. if ( count > buffer.Length - index ) {
  22. throw new ArgumentOutOfRangeException( "count" );
  23. }
  24. char[] chars = new char[ ( count * 2 ) < CharsChunkSize ? ( count * 2 ) : CharsChunkSize ];
  25. int endIndex = index + count;
  26. while ( index < endIndex ) {
  27. int cnt = ( count < CharsChunkSize/2 ) ? count : CharsChunkSize/2;
  28. int charCount = Encode( buffer, index, cnt, chars );
  29. writer.WriteRaw( chars, 0, charCount );
  30. index += cnt;
  31. count -= cnt;
  32. }
  33. }
  34. internal static string Encode(byte[] inArray, int offsetIn, int count) {
  35. if (null == inArray) {
  36. throw new ArgumentNullException("inArray");
  37. }
  38. if (0 > offsetIn) {
  39. throw new ArgumentOutOfRangeException("offsetIn");
  40. }
  41. if (0 > count) {
  42. throw new ArgumentOutOfRangeException("count");
  43. }
  44. if (count > inArray.Length - offsetIn) {
  45. throw new ArgumentOutOfRangeException("count");
  46. }
  47. char[] outArray = new char[2 * count];
  48. int lenOut = Encode(inArray, offsetIn, count, outArray);
  49. return new String(outArray, 0, lenOut);
  50. }
  51. private static int Encode(byte[] inArray, int offsetIn, int count, char[] outArray) {
  52. int curOffsetOut =0, offsetOut = 0;
  53. byte b;
  54. int lengthOut = outArray.Length;
  55. for (int j=0; j<count; j++) {
  56. b = inArray[offsetIn ++];
  57. outArray[curOffsetOut ++] = s_hexDigits[b >> 4];
  58. if (curOffsetOut == lengthOut) {
  59. break;
  60. }
  61. outArray[curOffsetOut ++] = s_hexDigits[b & 0xF];
  62. if (curOffsetOut == lengthOut) {
  63. break;
  64. }
  65. }
  66. return curOffsetOut - offsetOut;
  67. } // function
  68. } // class
  69. } // namespace