Skip to content

feat(Converter): add HexConverter/BinConverter static class#544

Merged
ArgoZhang merged 7 commits intomasterfrom
feat-socket
Aug 27, 2025
Merged

feat(Converter): add HexConverter/BinConverter static class#544
ArgoZhang merged 7 commits intomasterfrom
feat-socket

Conversation

@ArgoZhang
Copy link
Copy Markdown
Member

@ArgoZhang ArgoZhang commented Aug 27, 2025

Link issues

fixes #543

Summary By Copilot

Regression?

  • Yes
  • No

Risk

  • High
  • Medium
  • Low

Verification

  • Manual (required)
  • Automated

Packaging changes reviewed?

  • Yes
  • No
  • N/A

☑️ Self Check before Merge

⚠️ Please check all items below before review. ⚠️

  • Doc is updated/provided or not needed
  • Demo is updated/provided or not needed
  • Merge the latest code from the main branch

Summary by Sourcery

Add static HexConverter and BinConverter classes to convert between byte arrays and hexadecimal or binary strings, complete with validation and custom separators, and include unit tests for both converters

New Features:

  • Introduce HexConverter for byte array to hex string conversion and vice versa
  • Introduce BinConverter for byte array to binary string conversion and vice versa

Tests:

  • Add unit tests for HexConverter covering normal conversions and error conditions
  • Add unit tests for BinConverter covering normal conversions and error conditions

Copilot AI review requested due to automatic review settings August 27, 2025 01:25
@bb-auto bb-auto Bot added the enhancement New feature or request label Aug 27, 2025
@bb-auto bb-auto Bot added this to the v9.2.0 milestone Aug 27, 2025
@ArgoZhang ArgoZhang merged commit 9fe0f1e into master Aug 27, 2025
1 check passed
@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Aug 27, 2025

Reviewer's Guide

This PR introduces two static converter classes (HexConverter and BinConverter) for bidirectional transformations between byte arrays and their hexadecimal or binary string representations, adds corresponding unit tests, and updates the project file to include the new DataConverter folder.

Class diagram for new HexConverter and BinConverter static classes

classDiagram
    class HexConverter {
        +static string ToString(byte[]? bytes, string? separator = "-")
        +static byte[] ToBytes(string str, string? separator = null, StringSplitOptions options = StringSplitOptions.None)
    }
    class BinConverter {
        +static string ToString(byte[]? bytes, string? separator = "-")
        +static byte[] ToBytes(string str, string? separator = null, StringSplitOptions options = StringSplitOptions.None)
    }
Loading

File-Level Changes

Change Details Files
Update project to include DataConverter sources
  • Added DataConverter directory entry to .csproj
src/extensions/BootstrapBlazor.Socket/BootstrapBlazor.Socket.csproj
Introduce HexConverter static class
  • Implemented ToString with default/custom separators and null/empty handling
  • Implemented ToBytes with separator removal, length validation, and hex parsing
src/extensions/BootstrapBlazor.Socket/DataConverter/HexConverter.cs
Introduce BinConverter static class
  • Implemented ToString using LINQ to generate padded binary segments
  • Implemented ToBytes with splitting, padding, length validation, and binary parsing
src/extensions/BootstrapBlazor.Socket/DataConverter/BinConverter.cs
Add unit tests for converters
  • Tests for null/empty inputs and exception scenarios
  • Tests for default and custom separator conversions in both converters
test/UnitTestTcpSocket/HexConverterTest.cs
test/UnitTestTcpSocket/BinConverterTest.cs

Assessment against linked issues

Issue Objective Addressed Explanation
#543 Implement a static HexConverter class for converting between hexadecimal strings and byte arrays.
#543 Implement a static BinConverter class for converting between binary strings and byte arrays.

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@ArgoZhang ArgoZhang deleted the feat-socket branch August 27, 2025 01:25
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR adds two new static converter classes - HexConverter and BinConverter - to support conversion between byte arrays and their hexadecimal/binary string representations. These utilities address issue #543 by providing reusable conversion functionality for socket data processing.

  • Implements HexConverter for byte array ↔ hexadecimal string conversions
  • Implements BinConverter for byte array ↔ binary string conversions
  • Includes comprehensive unit tests for both converters

Reviewed Changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
src/extensions/BootstrapBlazor.Socket/DataConverter/HexConverter.cs Implements hexadecimal conversion utilities with customizable separators
src/extensions/BootstrapBlazor.Socket/DataConverter/BinConverter.cs Implements binary conversion utilities with customizable separators
test/UnitTestTcpSocket/HexConverterTest.cs Unit tests covering HexConverter functionality including edge cases
test/UnitTestTcpSocket/BinConverterTest.cs Unit tests covering BinConverter functionality including edge cases
src/extensions/BootstrapBlazor.Socket/BootstrapBlazor.Socket.csproj Version bump from 9.0.1 to 9.0.2

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

Comment on lines +16 to +20
/// <para>Converts a byte array to its hexadecimal string representation.</para>
/// </summary>
/// <param name="bytes">The byte array to convert.</param>
/// <param name="separator"></param>
/// <returns>A string containing the hexadecimal representation of the byte array.</returns>
Copy link

Copilot AI Aug 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The documentation comment incorrectly states 'hexadecimal string representation' when it should be 'binary string representation' for the BinConverter class.

Suggested change
/// <para>Converts a byte array to its hexadecimal string representation.</para>
/// </summary>
/// <param name="bytes">The byte array to convert.</param>
/// <param name="separator"></param>
/// <returns>A string containing the hexadecimal representation of the byte array.</returns>
/// <para>Converts a byte array to its binary string representation.</para>
/// </summary>
/// <param name="bytes">The byte array to convert.</param>
/// <param name="separator"></param>
/// <returns>A string containing the binary representation of the byte array.</returns>

Copilot uses AI. Check for mistakes.
/// </summary>
/// <param name="bytes">The byte array to convert.</param>
/// <param name="separator"></param>
/// <returns>A string containing the hexadecimal representation of the byte array.</returns>
Copy link

Copilot AI Aug 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The return documentation incorrectly states 'hexadecimal representation' when it should be 'binary representation' for the BinConverter class.

Suggested change
/// <returns>A string containing the hexadecimal representation of the byte array.</returns>
/// <returns>A string containing the binary representation of the byte array.</returns>

Copilot uses AI. Check for mistakes.
str = string.Join("", str.Split(separator, options).Select(i => i.PadLeft(8, '0')));
}

// 把 Hex 形式的 str 转化为 byte[]
Copy link

Copilot AI Aug 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comment incorrectly refers to 'Hex 形式的 str' (Hex format string) when it should refer to binary format string in the BinConverter class.

Suggested change
// 把 Hex 形式的 str 转化为 byte[]
// 把二进制形式的 str 转化为 byte[]

Copilot uses AI. Check for mistakes.
Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes - here's some feedback:

  • Update BinConverter’s XML docs and comments to refer to binary instead of hexadecimal for both ToString and ToBytes methods.
  • Simplify HexConverter.ToString by using string.Join on formatted bytes to handle custom or empty separators cleanly and avoid manual trimming logic.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Update BinConverter’s XML docs and comments to refer to binary instead of hexadecimal for both ToString and ToBytes methods.
- Simplify HexConverter.ToString by using string.Join on formatted bytes to handle custom or empty separators cleanly and avoid manual trimming logic.

## Individual Comments

### Comment 1
<location> `src/extensions/BootstrapBlazor.Socket/DataConverter/HexConverter.cs:39` </location>
<code_context>
+            sb.Append(b.ToString("X2"));
+            sb.Append(separator);
+        }
+        return sb.ToString(0, sb.Length - 1);
+    }
+
</code_context>

<issue_to_address>
Potential issue if separator is an empty string.

When separator is empty, the current logic omits the last byte. Please add a condition to handle empty separators to ensure correct output.
</issue_to_address>

### Comment 2
<location> `src/extensions/BootstrapBlazor.Socket/DataConverter/BinConverter.cs:43` </location>
<code_context>
+        // 把 str 内的 separator 符号替换掉
+        if (!string.IsNullOrEmpty(separator))
+        {
+            str = string.Join("", str.Split(separator, options).Select(i => i.PadLeft(8, '0')));
+        }
+
</code_context>

<issue_to_address>
Padding each split segment to 8 may mask input errors.

Validate segment lengths before padding to prevent masking malformed input.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
        // 把 str 内的 separator 符号替换掉
        if (!string.IsNullOrEmpty(separator))
        {
            str = string.Join("", str.Split(separator, options).Select(i => i.PadLeft(8, '0')));
        }
=======
        // 把 str 内的 separator 符号替换掉
        if (!string.IsNullOrEmpty(separator))
        {
            var segments = str.Split(separator, options);
            const int expectedLength = 8;
            foreach (var segment in segments)
            {
                if (segment.Length > expectedLength)
                {
                    throw new FormatException($"Segment '{segment}' length {segment.Length} exceeds expected length {expectedLength}.");
                }
            }
            str = string.Join("", segments.Select(i => i.PadLeft(expectedLength, '0')));
        }
>>>>>>> REPLACE

</suggested_fix>

### Comment 3
<location> `src/extensions/BootstrapBlazor.Socket/DataConverter/BinConverter.cs:47` </location>
<code_context>
+        }
+
+        // 把 Hex 形式的 str 转化为 byte[]
+        if (str.Length % 8 != 0)
+        {
+            throw new ArgumentException("The raw string cannot have an odd number of digits. 参数 str 位数不正确无法转化为 二进制字节数组", nameof(str));
</code_context>

<issue_to_address>
Exception message refers to 'odd number of digits' for binary conversion.

Update the exception message to specify that the string length must be a multiple of 8 for binary conversion.
</issue_to_address>

### Comment 4
<location> `test/UnitTestTcpSocket/BinConverterTest.cs:11` </location>
<code_context>
+
+public class BinConverterTest
+{
+    [Fact]
+    public void ToHexString_Null()
+    {
+        var actual = BinConverter.ToString(null);
+        Assert.Equal(string.Empty, actual);
+
+        actual = BinConverter.ToString([]);
+        Assert.Equal(string.Empty, actual);
+    }
+
+    [Fact]
+    public void ToBinString_Ok()
+    {
+        var data = new byte[] { 0x1A, 0x02 };
+        var actual = BinConverter.ToString(data);
+        Assert.Equal("00011010-00000010", actual);
+
+        actual = BinConverter.ToString(data, " ");
+        Assert.Equal("00011010 00000010", actual);
+    }
+
+    [Fact]
+    public void ToHexString_Exception()
+    {
+        var data = "00011010-00000010";
</code_context>

<issue_to_address>
Exception test does not cover valid binary string with odd length.

Please add a test for a raw binary string with odd length, such as "0001101", to verify the exception is correctly thrown in this case.
</issue_to_address>

### Comment 5
<location> `test/UnitTestTcpSocket/HexConverterTest.cs:11` </location>
<code_context>
+
+public class BinConverterTest
+{
+    [Fact]
+    public void ToHexString_Null()
+    {
+        var actual = BinConverter.ToString(null);
+        Assert.Equal(string.Empty, actual);
+
+        actual = BinConverter.ToString([]);
+        Assert.Equal(string.Empty, actual);
+    }
+
+    [Fact]
+    public void ToBinString_Ok()
+    {
+        var data = new byte[] { 0x1A, 0x02 };
+        var actual = BinConverter.ToString(data);
+        Assert.Equal("00011010-00000010", actual);
+
+        actual = BinConverter.ToString(data, " ");
+        Assert.Equal("00011010 00000010", actual);
+    }
+
+    [Fact]
+    public void ToHexString_Exception()
+    {
+        var data = "00011010-00000010";
</code_context>

<issue_to_address>
Exception test does not cover valid hex string with odd length and with separators.

Please add a test with a hex string containing separators that results in an odd digit count after removing separators, to verify the exception is correctly thrown in this case.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

sb.Append(b.ToString("X2"));
sb.Append(separator);
}
return sb.ToString(0, sb.Length - 1);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue: Potential issue if separator is an empty string.

When separator is empty, the current logic omits the last byte. Please add a condition to handle empty separators to ensure correct output.

Comment on lines +40 to +44
// 把 str 内的 separator 符号替换掉
if (!string.IsNullOrEmpty(separator))
{
str = string.Join("", str.Split(separator, options).Select(i => i.PadLeft(8, '0')));
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (bug_risk): Padding each split segment to 8 may mask input errors.

Validate segment lengths before padding to prevent masking malformed input.

Suggested change
// 把 str 内的 separator 符号替换掉
if (!string.IsNullOrEmpty(separator))
{
str = string.Join("", str.Split(separator, options).Select(i => i.PadLeft(8, '0')));
}
// 把 str 内的 separator 符号替换掉
if (!string.IsNullOrEmpty(separator))
{
var segments = str.Split(separator, options);
const int expectedLength = 8;
foreach (var segment in segments)
{
if (segment.Length > expectedLength)
{
throw new FormatException($"Segment '{segment}' length {segment.Length} exceeds expected length {expectedLength}.");
}
}
str = string.Join("", segments.Select(i => i.PadLeft(expectedLength, '0')));
}

}

// 把 Hex 形式的 str 转化为 byte[]
if (str.Length % 8 != 0)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick: Exception message refers to 'odd number of digits' for binary conversion.

Update the exception message to specify that the string length must be a multiple of 8 for binary conversion.

Comment on lines +11 to +20
[Fact]
public void ToHexString_Null()
{
var actual = BinConverter.ToString(null);
Assert.Equal(string.Empty, actual);

actual = BinConverter.ToString([]);
Assert.Equal(string.Empty, actual);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (testing): Exception test does not cover valid binary string with odd length.

Please add a test for a raw binary string with odd length, such as "0001101", to verify the exception is correctly thrown in this case.

Comment on lines +11 to +20
[Fact]
public void ToHexString_Null()
{
var actual = HexConverter.ToString(null);
Assert.Equal(string.Empty, actual);

actual = HexConverter.ToString([]);
Assert.Equal(string.Empty, actual);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (testing): Exception test does not cover valid hex string with odd length and with separators.

Please add a test with a hex string containing separators that results in an odd digit count after removing separators, to verify the exception is correctly thrown in this case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(Converter): add HexConverter/BinConverter static class

2 participants