GBA.Unity/Assets/MyUnSafeCommon.cs
2024-08-15 13:19:43 +08:00

91 lines
3.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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)
{
// 确保旋转位数在有效范围内对于uint0到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)
{
// 确保旋转位数在有效范围内对于ulong0到63
count &= 63;
// 使用位移和位或操作来实现旋转
// 注意ulong需要64位操作
ulong rightShifted = value >> count;
ulong leftShifted = (value << (64 - count)) & 0xFFFFFFFFFFFFFFFF; // 同样对于ulong& 0xFFFFFFFFFFFFFFFF是多余的但保留以增加清晰性
// 组合结果
return rightShifted | leftShifted;
}
}