91 lines
3.2 KiB
C#
91 lines
3.2 KiB
C#
|
using System;
|
|||
|
|
|||
|
public static class MyUnSafeCommon
|
|||
|
{
|
|||
|
public static ref T GetArrayDataReference<T>(T[] array)
|
|||
|
{
|
|||
|
if (array == null) throw new ArgumentNullException(nameof(array));
|
|||
|
if (array.Length == 0) throw new ArgumentException("Array cannot be empty", nameof(array));
|
|||
|
return ref array[0];
|
|||
|
}
|
|||
|
|
|||
|
//public unsafe static ref T GetArrayDataReference<T>(T[] array) where T : struct
|
|||
|
//{
|
|||
|
// fixed (T* ptr = array)
|
|||
|
// {
|
|||
|
// return ref ArrayElementAsRef<T>(ptr, 0);
|
|||
|
// }
|
|||
|
//}
|
|||
|
|
|||
|
//public unsafe static ref T ArrayElementAsRef<T>(void* ptr, int index) where T : struct
|
|||
|
//{
|
|||
|
// return ref Unity.Collections.LowLevel.Unsafe.UnsafeUtility.ArrayElementAsRef<T>(ptr, index);
|
|||
|
//}
|
|||
|
|
|||
|
}
|
|||
|
|
|||
|
|
|||
|
public static class MyBitOperations
|
|||
|
{
|
|||
|
// 计算一个整数的位计数(也称为汉明重量)
|
|||
|
public static int PopCount(uint value)
|
|||
|
{
|
|||
|
int count = 0;
|
|||
|
while (value != 0)
|
|||
|
{
|
|||
|
value &= value - 1; // 清除最低位的1
|
|||
|
count++;
|
|||
|
}
|
|||
|
return count;
|
|||
|
}
|
|||
|
|
|||
|
// 如果需要处理long或int等其他类型,可以添加重载
|
|||
|
public static int PopCount(int value)
|
|||
|
{
|
|||
|
return PopCount((uint)value); // 对于int,简单地将其视为无符号的uint来处理
|
|||
|
}
|
|||
|
|
|||
|
// 对于long,你可能需要更复杂的处理或额外的迭代,但基本思想相同
|
|||
|
public static int PopCount(long value)
|
|||
|
{
|
|||
|
int count = 0;
|
|||
|
value = value - ((value >> 1) & 0x5555555555555555L); // 每两位一组求和
|
|||
|
value = (value & 0x3333333333333333L) + ((value >> 2) & 0x3333333333333333L); // 每四位一组求和
|
|||
|
value = (value + (value >> 4)) & 0x0f0f0f0f0f0f0f0fL; // 每八位一组求和
|
|||
|
count = (int)((value * 0x0101010101010101L) >> 56); // 计算总和
|
|||
|
return count;
|
|||
|
}
|
|||
|
|
|||
|
// 向右旋转指定数量的位(等效于BitOperations.RotateRight)
|
|||
|
public static uint RotateRight(uint value, int count)
|
|||
|
{
|
|||
|
// 确保旋转位数在有效范围内(对于uint,0到31)
|
|||
|
count &= 31;
|
|||
|
|
|||
|
// 使用位移和位或操作来实现旋转
|
|||
|
// 先右移count位
|
|||
|
uint rightShifted = value >> count;
|
|||
|
|
|||
|
// 然后左移(32 - count)位,并将结果与右移的结果进行位或操作
|
|||
|
// 注意:由于uint是无符号的,所以左移不会导致符号扩展
|
|||
|
uint leftShifted = (value << (32 - count)) & 0xFFFFFFFF; // 实际上,对于uint,& 0xFFFFFFFF是多余的,但在这里为了清晰性而保留
|
|||
|
|
|||
|
// 组合结果
|
|||
|
return rightShifted | leftShifted;
|
|||
|
}
|
|||
|
|
|||
|
// 如果需要处理ulong,可以添加类似的重载
|
|||
|
public static ulong RotateRight(ulong value, int count)
|
|||
|
{
|
|||
|
// 确保旋转位数在有效范围内(对于ulong,0到63)
|
|||
|
count &= 63;
|
|||
|
|
|||
|
// 使用位移和位或操作来实现旋转
|
|||
|
// 注意:ulong需要64位操作
|
|||
|
ulong rightShifted = value >> count;
|
|||
|
ulong leftShifted = (value << (64 - count)) & 0xFFFFFFFFFFFFFFFF; // 同样,对于ulong,& 0xFFFFFFFFFFFFFFFF是多余的,但保留以增加清晰性
|
|||
|
|
|||
|
// 组合结果
|
|||
|
return rightShifted | leftShifted;
|
|||
|
}
|
|||
|
}
|