CSharp · Console
using System;
using System.Text;
using System.Linq;
using System.Buffers.Binary;
public class Program
{
delegate int BytesComparer(ReadOnlySpan<byte> a, ReadOnlySpan<byte> b);
static int BinarySearchRecord(byte[] array, int recordWidth, ReadOnlySpan<byte> value, BytesComparer comparer)
{
return BinarySearchRecord(array, 0, array.Length / recordWidth, recordWidth, value, comparer);
}
static int BinarySearchRecord(byte[] array, int startRecord, int count, int recordWidth, ReadOnlySpan<byte> value, BytesComparer comparer)
{
int lo = startRecord;
int hi = startRecord + count - 1;
while (lo <= hi)
{
int i = lo + ((hi - lo) >> 1);
int order = comparer(new ReadOnlySpan<byte>(array, i * recordWidth, recordWidth), value);
if (order == 0) return i;
if (order < 0)
lo = i + 1;
else
hi = i - 1;
}
return ~lo;
}
public static void Main()
{
var yourArray = Encoding.ASCII.GetBytes("ABLE xxxxBAKER xxxxCARL xxxxDELTA xxxxEDGAR xxxxGEORGExxxx");
var valToFind = Encoding.ASCII.GetBytes("DELTA ").Concat(new byte[]{0x1, 0x2, 0x3, 0x4}).ToArray();
var foundIndex = BinarySearchRecord(yourArray, valToFind.Length, new ReadOnlySpan<byte>(valToFind), (a, b) =>
{
var ret = BinaryPrimitives.ReverseEndianness(BitConverter.ToInt64(a) & 0x0000ffffffffffff)
.CompareTo(
BinaryPrimitives.ReverseEndianness(BitConverter.ToInt64(b) & 0x0000ffffffffffff));
Console.WriteLine(ret);
return ret;
});
Console.WriteLine(foundIndex);
}
}