PageRenderTime 42ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/DICOM/IO/ByteConverter.cs

https://github.com/petnet/fo-dicom
C# | 82 lines | 69 code | 13 blank | 0 comment | 11 complexity | 4e7c7e2051636aa2a7db83c108546183 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. using Dicom.IO.Buffer;
  7. using Dicom.Imaging.Mathematics
  8. ;
  9. namespace Dicom.IO {
  10. public static class ByteConverter {
  11. public static IByteBuffer ToByteBuffer(string value, Encoding encoding=null) {
  12. if (encoding == null)
  13. encoding = Encoding.ASCII;
  14. byte[] bytes = encoding.GetBytes(value);
  15. return new MemoryByteBuffer(bytes);
  16. }
  17. public static IByteBuffer ToByteBuffer(string value, Encoding encoding, byte padding) {
  18. if (encoding == null)
  19. encoding = Encoding.ASCII;
  20. byte[] bytes = Encoding.ASCII.GetBytes(value);
  21. if (bytes.Length.IsOdd()) {
  22. Array.Resize(ref bytes, bytes.Length + 1);
  23. bytes[bytes.Length - 1] = padding;
  24. }
  25. return new MemoryByteBuffer(bytes);
  26. }
  27. public static IByteBuffer ToByteBuffer<T>(T[] values) where T: struct {
  28. int size = System.Buffer.ByteLength(values);
  29. byte[] data = new byte[size];
  30. System.Buffer.BlockCopy(values, 0, data, 0, size);
  31. return new MemoryByteBuffer(data);
  32. }
  33. public static T[] ToArray<T>(IByteBuffer buffer) {
  34. uint size = (uint)Marshal.SizeOf(typeof(T));
  35. uint padding = buffer.Size % size;
  36. uint count = buffer.Size / size;
  37. T[] values = new T[count];
  38. System.Buffer.BlockCopy(buffer.Data, 0, values, 0, (int)(buffer.Size - padding));
  39. return values;
  40. }
  41. public static T Get<T>(IByteBuffer buffer, int n) {
  42. int size = Marshal.SizeOf(typeof(T));
  43. T[] values = new T[1];
  44. if (buffer.IsMemory)
  45. System.Buffer.BlockCopy(buffer.Data, size * n, values, 0, size);
  46. else {
  47. byte[] temp = buffer.GetByteRange(size * n, size);
  48. System.Buffer.BlockCopy(temp, 0, values, 0, size);
  49. }
  50. return values[0];
  51. }
  52. public static IByteBuffer UnpackLow16(IByteBuffer data) {
  53. byte[] bytes = new byte[data.Size / 2];
  54. byte[] datab = data.Data;
  55. for (int i = 0; i < bytes.Length && (i * 2) < datab.Length; i++) {
  56. bytes[i] = datab[i * 2];
  57. }
  58. return new MemoryByteBuffer(bytes);
  59. }
  60. public static IByteBuffer UnpackHigh16(IByteBuffer data) {
  61. byte[] bytes = new byte[data.Size / 2];
  62. byte[] datab = data.Data;
  63. for (int i = 0; i < bytes.Length && ((i * 2) + 1) < datab.Length; i++) {
  64. bytes[i] = datab[(i * 2) + 1];
  65. }
  66. return new MemoryByteBuffer(bytes);
  67. }
  68. }
  69. }