快乐宝爸 發表於 2025-7-22 11:04:00

C#中有符号整数与无符号整数之间的二进制值拷贝

<p>因为我现在需要将<code>uint</code>作为字典的键进行存储,这就需要编写一个<code>GetHashCode()</code>,那么最好的办法就是直接把它的二进制值拷贝为1个<code>int</code>。</p>
<p>这里给出我的<code>int</code>和<code>uint</code>之间的直接拷贝方法:</p>
<pre><code class="language-csharp">int x;
uint y;
y = BitConverter.ToUInt32(BitConverter.GetBytes(x), 0);
x = BitConverter.ToInt32(BitConverter.GetBytes(y), 0);
</code></pre>
<p>那么<code>GetHashCode()</code>就长这样了:</p>
<pre><code class="language-csharp">using System;
public interface IIdUsingUInt32
{
        Int32 id { get; set; }// 为了适配数据库的命名风格,并避免命名转换,这里直接使用下划线命名法。

        public class EqualityComparer : IEqualityComparer&lt;IIdUsingUInt32&gt;
        {
                public bool Equals(IIdUsingUInt32 x, IIdUsingUInt32 y) =&gt; x.id == y.id;

                public int GetHashCode(IIdUsingUInt32 obj) =&gt; BitConverter.ToInt32(BitConverter.GetBytes(obj.id), 0);
        }
}
</code></pre>


</div>
<div id="MySignature" role="contentinfo">
    <p>本文来自博客园,作者:Orange233,转载请注明原文链接:https://www.cnblogs.com/orange233/p/18997397/convert-between-unsigned-and-signed-value-by-directly-copy-its-binary-value</p><br><br>
来源:https://www.cnblogs.com/orange233/p/18997397/convert-between-unsigned-and-signed-value-by-directly-copy-its-binary-value
頁: [1]
查看完整版本: C#中有符号整数与无符号整数之间的二进制值拷贝