|
| 1 | +// Copyright (c) BootstrapBlazor & Argo Zhang (argo@live.ca). All rights reserved. |
| 2 | +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. |
| 3 | +// Website: https://www.blazor.zone or https://argozhang.github.io/ |
| 4 | + |
| 5 | +using System.Text; |
| 6 | + |
| 7 | +namespace BootstrapBlazor.Components.DataConverter; |
| 8 | + |
| 9 | +/// <summary> |
| 10 | +/// 二进制 与 Byte 数组转换方法 |
| 11 | +/// </summary> |
| 12 | +public static class BinConverter |
| 13 | +{ |
| 14 | + /// <summary> |
| 15 | + /// 将 byte[] 转为 二进制字符串 |
| 16 | + /// <para>Converts a byte array to its hexadecimal string representation.</para> |
| 17 | + /// </summary> |
| 18 | + /// <param name="bytes">The byte array to convert.</param> |
| 19 | + /// <param name="separator"></param> |
| 20 | + /// <returns>A string containing the hexadecimal representation of the byte array.</returns> |
| 21 | + public static string ToString(byte[]? bytes, string? separator = "-") |
| 22 | + { |
| 23 | + if (bytes == null || bytes.Length == 0) |
| 24 | + { |
| 25 | + return string.Empty; |
| 26 | + } |
| 27 | + |
| 28 | + return string.Join(separator, bytes.Select(i => Convert.ToString(i, 2).PadLeft(8, '0'))); |
| 29 | + } |
| 30 | + |
| 31 | + /// <summary> |
| 32 | + /// 将字符串转换为字节数组 |
| 33 | + /// </summary> |
| 34 | + /// <param name="str"></param> |
| 35 | + /// <param name="separator"></param> |
| 36 | + /// <param name="options"></param> |
| 37 | + /// <returns></returns> |
| 38 | + public static byte[] ToBytes(string str, string? separator = null, StringSplitOptions options = StringSplitOptions.None) |
| 39 | + { |
| 40 | + // 把 str 内的 delimiter 符号替换掉 |
| 41 | + if (!string.IsNullOrEmpty(separator)) |
| 42 | + { |
| 43 | + str = string.Join("", str.Split(separator, options).Select(i => i.PadLeft(8, '0'))); |
| 44 | + } |
| 45 | + |
| 46 | + // 把 Hex 形式的 str 转化为 byte[] |
| 47 | + if (str.Length % 8 != 0) |
| 48 | + { |
| 49 | + throw new ArgumentException("The raw string cannot have an odd number of digits. 参数 str 位数不正确无法转化为 二进制字节数组", nameof(str)); |
| 50 | + } |
| 51 | + |
| 52 | + var bytes = new byte[str.Length / 8]; |
| 53 | + for (var i = 0; i < bytes.Length; i++) |
| 54 | + { |
| 55 | + bytes[i] = Convert.ToByte(str.Substring(i * 8, 8), 2); |
| 56 | + } |
| 57 | + return bytes; |
| 58 | + } |
| 59 | +} |
0 commit comments