NET问答: 如何使用 C# 比较两个 byte[] 的相等性 ?
生活随笔
收集整理的這篇文章主要介紹了
NET问答: 如何使用 C# 比较两个 byte[] 的相等性 ?
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
咨詢區(qū)
Hafthor:
我現(xiàn)在業(yè)務中遇到了一個場景:如何簡潔高效的判斷兩個 byte[] 的相等性?我現(xiàn)在是這么實現(xiàn)的,有一點繁瑣:
static?bool?ByteArrayCompare(byte[]?a1,?byte[]?a2) {if?(a1.Length?!=?a2.Length)return?false;for?(int?i=0;?i<a1.Length;?i++)if?(a1[i]!=a2[i])return?false;return?true; }在 java 中是可以非常方便的實現(xiàn)。
java.util.Arrays.equals((sbyte[])(Array)a1,?(sbyte[])(Array)a2);回答區(qū)
aku:
其實你可以使用 Linq 提供的 Enumerable.SequenceEqual 擴展方法達到同樣的快捷效果。
using?System; using?System.Linq; ... var?a1?=?new?int[]?{?1,?2,?3}; var?a2?=?new?int[]?{?1,?2,?3}; var?a3?=?new?int[]?{?1,?2,?4}; var?x?=?a1.SequenceEqual(a2);?//?true var?y?=?a1.SequenceEqual(a3);?//?false順便提醒一下:編譯器和運行時 會優(yōu)化這種 loop 循環(huán),所以你不需要擔心什么性能問題。
plinth:
可以借助 Windows 自帶的系統(tǒng)函數(shù)幫你搞定,你要做的就是用 P/Invoke 調它,參考代碼如下:
[DllImport("msvcrt.dll",?CallingConvention=CallingConvention.Cdecl)] static?extern?int?memcmp(byte[]?b1,?byte[]?b2,?long?count);static?bool?ByteArrayCompare(byte[]?b1,?byte[]?b2) {//?Validate?buffers?are?the?same?length.//?This?also?ensures?that?the?count?does?not?exceed?the?length?of?either?buffer.??return?b1.Length?==?b2.Length?&&?memcmp(b1,?b2,?b1.Length)?==?0; }或者你可以自己封裝一段 unsafe 的代碼。
//?Copyright?(c)?2008-2013?Hafthor?Stefansson //?Distributed?under?the?MIT/X11?software?license //?Ref:?http://www.opensource.org/licenses/mit-license.php. static?unsafe?bool?UnsafeCompare(byte[]?a1,?byte[]?a2)?{if(a1==a2)?return?true;if(a1==null?||?a2==null?||?a1.Length!=a2.Length)return?false;fixed?(byte*?p1=a1,?p2=a2)?{byte*?x1=p1,?x2=p2;int?l?=?a1.Length;for?(int?i=0;?i?<?l/8;?i++,?x1+=8,?x2+=8)if?(*((long*)x1)?!=?*((long*)x2))?return?false;if?((l?&?4)!=0)?{?if?(*((int*)x1)!=*((int*)x2))?return?false;?x1+=4;?x2+=4;?}if?((l?&?2)!=0)?{?if?(*((short*)x1)!=*((short*)x2))?return?false;?x1+=2;?x2+=2;?}if?((l?&?1)!=0)?if?(*((byte*)x1)?!=?*((byte*)x2))?return?false;return?true;} }點評區(qū)
plinth 大佬的想法別出心裁,借助現(xiàn)存強大的 Windows 系統(tǒng)函數(shù),免去了很多重復的業(yè)務邏輯,簡單粗暴又高效,學習了。
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結
以上是生活随笔為你收集整理的NET问答: 如何使用 C# 比较两个 byte[] 的相等性 ?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: NET问答: String 和 stri
- 下一篇: c# char unsigned_dll