BitConverter.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Diagnostics;
  5. using System.Runtime.CompilerServices;
  6. using System.Runtime.InteropServices;
  7. using Internal.Runtime.CompilerServices;
  8. namespace System
  9. {
  10. // The BitConverter class contains methods for
  11. // converting an array of bytes to one of the base data
  12. // types, as well as for converting a base data type to an
  13. // array of bytes.
  14. public static class BitConverter
  15. {
  16. // This field indicates the "endianess" of the architecture.
  17. // The value is set to true if the architecture is
  18. // little endian; false if it is big endian.
  19. #if BIGENDIAN
  20. public static readonly bool IsLittleEndian /* = false */;
  21. #else
  22. public static readonly bool IsLittleEndian = true;
  23. #endif
  24. // Converts a Boolean into an array of bytes with length one.
  25. public static byte[] GetBytes(bool value)
  26. {
  27. byte[] r = new byte[1];
  28. r[0] = (value ? (byte)1 : (byte)0);
  29. return r;
  30. }
  31. // Converts a Boolean into a Span of bytes with length one.
  32. public static bool TryWriteBytes(Span<byte> destination, bool value)
  33. {
  34. if (destination.Length < sizeof(byte))
  35. return false;
  36. Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value ? (byte)1 : (byte)0);
  37. return true;
  38. }
  39. // Converts a char into an array of bytes with length two.
  40. public static byte[] GetBytes(char value)
  41. {
  42. byte[] bytes = new byte[sizeof(char)];
  43. Unsafe.As<byte, char>(ref bytes[0]) = value;
  44. return bytes;
  45. }
  46. // Converts a char into a Span
  47. public static bool TryWriteBytes(Span<byte> destination, char value)
  48. {
  49. if (destination.Length < sizeof(char))
  50. return false;
  51. Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
  52. return true;
  53. }
  54. // Converts a short into an array of bytes with length
  55. // two.
  56. public static byte[] GetBytes(short value)
  57. {
  58. byte[] bytes = new byte[sizeof(short)];
  59. Unsafe.As<byte, short>(ref bytes[0]) = value;
  60. return bytes;
  61. }
  62. // Converts a short into a Span
  63. public static bool TryWriteBytes(Span<byte> destination, short value)
  64. {
  65. if (destination.Length < sizeof(short))
  66. return false;
  67. Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
  68. return true;
  69. }
  70. // Converts an int into an array of bytes with length
  71. // four.
  72. public static byte[] GetBytes(int value)
  73. {
  74. byte[] bytes = new byte[sizeof(int)];
  75. Unsafe.As<byte, int>(ref bytes[0]) = value;
  76. return bytes;
  77. }
  78. // Converts an int into a Span
  79. public static bool TryWriteBytes(Span<byte> destination, int value)
  80. {
  81. if (destination.Length < sizeof(int))
  82. return false;
  83. Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
  84. return true;
  85. }
  86. // Converts a long into an array of bytes with length
  87. // eight.
  88. public static byte[] GetBytes(long value)
  89. {
  90. byte[] bytes = new byte[sizeof(long)];
  91. Unsafe.As<byte, long>(ref bytes[0]) = value;
  92. return bytes;
  93. }
  94. // Converts a long into a Span
  95. public static bool TryWriteBytes(Span<byte> destination, long value)
  96. {
  97. if (destination.Length < sizeof(long))
  98. return false;
  99. Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
  100. return true;
  101. }
  102. // Converts an ushort into an array of bytes with
  103. // length two.
  104. [CLSCompliant(false)]
  105. public static byte[] GetBytes(ushort value)
  106. {
  107. byte[] bytes = new byte[sizeof(ushort)];
  108. Unsafe.As<byte, ushort>(ref bytes[0]) = value;
  109. return bytes;
  110. }
  111. // Converts a ushort into a Span
  112. [CLSCompliant(false)]
  113. public static bool TryWriteBytes(Span<byte> destination, ushort value)
  114. {
  115. if (destination.Length < sizeof(ushort))
  116. return false;
  117. Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
  118. return true;
  119. }
  120. // Converts an uint into an array of bytes with
  121. // length four.
  122. [CLSCompliant(false)]
  123. public static byte[] GetBytes(uint value)
  124. {
  125. byte[] bytes = new byte[sizeof(uint)];
  126. Unsafe.As<byte, uint>(ref bytes[0]) = value;
  127. return bytes;
  128. }
  129. // Converts a uint into a Span
  130. [CLSCompliant(false)]
  131. public static bool TryWriteBytes(Span<byte> destination, uint value)
  132. {
  133. if (destination.Length < sizeof(uint))
  134. return false;
  135. Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
  136. return true;
  137. }
  138. // Converts an unsigned long into an array of bytes with
  139. // length eight.
  140. [CLSCompliant(false)]
  141. public static byte[] GetBytes(ulong value)
  142. {
  143. byte[] bytes = new byte[sizeof(ulong)];
  144. Unsafe.As<byte, ulong>(ref bytes[0]) = value;
  145. return bytes;
  146. }
  147. // Converts a ulong into a Span
  148. [CLSCompliant(false)]
  149. public static bool TryWriteBytes(Span<byte> destination, ulong value)
  150. {
  151. if (destination.Length < sizeof(ulong))
  152. return false;
  153. Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
  154. return true;
  155. }
  156. // Converts a float into an array of bytes with length
  157. // four.
  158. public static byte[] GetBytes(float value)
  159. {
  160. byte[] bytes = new byte[sizeof(float)];
  161. Unsafe.As<byte, float>(ref bytes[0]) = value;
  162. return bytes;
  163. }
  164. // Converts a float into a Span
  165. public static bool TryWriteBytes(Span<byte> destination, float value)
  166. {
  167. if (destination.Length < sizeof(float))
  168. return false;
  169. Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
  170. return true;
  171. }
  172. // Converts a double into an array of bytes with length
  173. // eight.
  174. public static byte[] GetBytes(double value)
  175. {
  176. byte[] bytes = new byte[sizeof(double)];
  177. Unsafe.As<byte, double>(ref bytes[0]) = value;
  178. return bytes;
  179. }
  180. // Converts a double into a Span
  181. public static bool TryWriteBytes(Span<byte> destination, double value)
  182. {
  183. if (destination.Length < sizeof(double))
  184. return false;
  185. Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
  186. return true;
  187. }
  188. // Converts an array of bytes into a char.
  189. public static char ToChar(byte[] value, int startIndex) => unchecked((char)ToInt16(value, startIndex));
  190. // Converts a Span into a char
  191. public static char ToChar(ReadOnlySpan<byte> value)
  192. {
  193. if (value.Length < sizeof(char))
  194. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
  195. return Unsafe.ReadUnaligned<char>(ref MemoryMarshal.GetReference(value));
  196. }
  197. // Converts an array of bytes into a short.
  198. public static short ToInt16(byte[] value, int startIndex)
  199. {
  200. if (value == null)
  201. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
  202. if (unchecked((uint)startIndex) >= unchecked((uint)value.Length))
  203. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
  204. if (startIndex > value.Length - sizeof(short))
  205. ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value);
  206. return Unsafe.ReadUnaligned<short>(ref value[startIndex]);
  207. }
  208. // Converts a Span into a short
  209. public static short ToInt16(ReadOnlySpan<byte> value)
  210. {
  211. if (value.Length < sizeof(short))
  212. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
  213. return Unsafe.ReadUnaligned<short>(ref MemoryMarshal.GetReference(value));
  214. }
  215. // Converts an array of bytes into an int.
  216. public static int ToInt32(byte[] value, int startIndex)
  217. {
  218. if (value == null)
  219. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
  220. if (unchecked((uint)startIndex) >= unchecked((uint)value.Length))
  221. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
  222. if (startIndex > value.Length - sizeof(int))
  223. ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value);
  224. return Unsafe.ReadUnaligned<int>(ref value[startIndex]);
  225. }
  226. // Converts a Span into an int
  227. public static int ToInt32(ReadOnlySpan<byte> value)
  228. {
  229. if (value.Length < sizeof(int))
  230. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
  231. return Unsafe.ReadUnaligned<int>(ref MemoryMarshal.GetReference(value));
  232. }
  233. // Converts an array of bytes into a long.
  234. public static long ToInt64(byte[] value, int startIndex)
  235. {
  236. if (value == null)
  237. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
  238. if (unchecked((uint)startIndex) >= unchecked((uint)value.Length))
  239. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
  240. if (startIndex > value.Length - sizeof(long))
  241. ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value);
  242. return Unsafe.ReadUnaligned<long>(ref value[startIndex]);
  243. }
  244. // Converts a Span into a long
  245. public static long ToInt64(ReadOnlySpan<byte> value)
  246. {
  247. if (value.Length < sizeof(long))
  248. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
  249. return Unsafe.ReadUnaligned<long>(ref MemoryMarshal.GetReference(value));
  250. }
  251. // Converts an array of bytes into an ushort.
  252. //
  253. [CLSCompliant(false)]
  254. public static ushort ToUInt16(byte[] value, int startIndex) => unchecked((ushort)ToInt16(value, startIndex));
  255. // Converts a Span into a ushort
  256. [CLSCompliant(false)]
  257. public static ushort ToUInt16(ReadOnlySpan<byte> value)
  258. {
  259. if (value.Length < sizeof(ushort))
  260. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
  261. return Unsafe.ReadUnaligned<ushort>(ref MemoryMarshal.GetReference(value));
  262. }
  263. // Converts an array of bytes into an uint.
  264. //
  265. [CLSCompliant(false)]
  266. public static uint ToUInt32(byte[] value, int startIndex) => unchecked((uint)ToInt32(value, startIndex));
  267. // Convert a Span into a uint
  268. [CLSCompliant(false)]
  269. public static uint ToUInt32(ReadOnlySpan<byte> value)
  270. {
  271. if (value.Length < sizeof(uint))
  272. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
  273. return Unsafe.ReadUnaligned<uint>(ref MemoryMarshal.GetReference(value));
  274. }
  275. // Converts an array of bytes into an unsigned long.
  276. //
  277. [CLSCompliant(false)]
  278. public static ulong ToUInt64(byte[] value, int startIndex) => unchecked((ulong)ToInt64(value, startIndex));
  279. // Converts a Span into an unsigned long
  280. [CLSCompliant(false)]
  281. public static ulong ToUInt64(ReadOnlySpan<byte> value)
  282. {
  283. if (value.Length < sizeof(ulong))
  284. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
  285. return Unsafe.ReadUnaligned<ulong>(ref MemoryMarshal.GetReference(value));
  286. }
  287. // Converts an array of bytes into a float.
  288. public static float ToSingle(byte[] value, int startIndex) => Int32BitsToSingle(ToInt32(value, startIndex));
  289. // Converts a Span into a float
  290. public static float ToSingle(ReadOnlySpan<byte> value)
  291. {
  292. if (value.Length < sizeof(float))
  293. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
  294. return Unsafe.ReadUnaligned<float>(ref MemoryMarshal.GetReference(value));
  295. }
  296. // Converts an array of bytes into a double.
  297. public static double ToDouble(byte[] value, int startIndex) => Int64BitsToDouble(ToInt64(value, startIndex));
  298. // Converts a Span into a double
  299. public static double ToDouble(ReadOnlySpan<byte> value)
  300. {
  301. if (value.Length < sizeof(double))
  302. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
  303. return Unsafe.ReadUnaligned<double>(ref MemoryMarshal.GetReference(value));
  304. }
  305. /*==================================ToBoolean===================================
  306. **Action: Convert an array of bytes to a boolean value. We treat this array
  307. ** as if the first 4 bytes were an Int4 an operate on this value.
  308. **Returns: True if the Int4 value of the first 4 bytes is non-zero.
  309. **Arguments: value -- The byte array
  310. ** startIndex -- The position within the array.
  311. **Exceptions: See ToInt4.
  312. ==============================================================================*/
  313. // Converts an array of bytes into a boolean.
  314. public static bool ToBoolean(byte[] value, int startIndex)
  315. {
  316. if (value == null)
  317. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
  318. if (startIndex < 0)
  319. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
  320. if (startIndex > value.Length - 1)
  321. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); // differs from other overloads, which throw base ArgumentException
  322. return value[startIndex] != 0;
  323. }
  324. public static bool ToBoolean(ReadOnlySpan<byte> value)
  325. {
  326. if (value.Length < sizeof(byte))
  327. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
  328. return Unsafe.ReadUnaligned<byte>(ref MemoryMarshal.GetReference(value)) != 0;
  329. }
  330. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  331. public static unsafe long DoubleToInt64Bits(double value)
  332. {
  333. return *((long*)&value);
  334. }
  335. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  336. public static unsafe double Int64BitsToDouble(long value)
  337. {
  338. return *((double*)&value);
  339. }
  340. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  341. public static unsafe int SingleToInt32Bits(float value)
  342. {
  343. return *((int*)&value);
  344. }
  345. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  346. public static unsafe float Int32BitsToSingle(int value)
  347. {
  348. return *((float*)&value);
  349. }
  350. }
  351. }