数字在指定位置指定位数的交换是常见算法。
1 源程序
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
namespace Legalsoft.Truffer.Algorithm
{
public static partial class Algorithm_Gallery
{
/// <summary>
///
/// </summary>
/// <param name="x">数字</param>
/// <param name="p1">位置1</param>
/// <param name="p2">位置2</param>
/// <param name="n">交换字节数目</param>
/// <returns></returns>
public static int Bits_Swap(int x, int p1, int p2, int n)
{
int set1 = (x >> p1) & ((1 << n) - 1);
int set2 = (x >> p2) & ((1 << n) - 1);
int xor = (set1 ^ set2);
xor = (xor << p1) | (xor << p2);
int result = x ^ xor;
return result;
}
public static int Bits_Swap_Second(int x, int p1, int p2, int n)
{
int xor = (int)(((x >> p1) ^ (x >> p2)) & ((1U << n) - 1));
return x ^ ((xor << p1) | (xor << p2));
}
public static int Bits_Swap_Third(int x, int p1, int p2, int n)
{
int shift1, shift2, value1, value2;
while ((n--) > 0)
{
shift1 = 1 << p1;
shift2 = 1 << p2;
value1 = ((x & shift1));
value2 = ((x & shift2));
if ((value1 == 0 && value2 != 0) || (value2 == 0 && value1 != 0))
{
if (value1 != 0)
{
x = x & (~shift1);
x = x | shift2;
}
else
{
x = x & (~shift2);
x = x | shift1;
}
}
p1++;
p2++;
}
return x;
}
}
}
POWER BY TRUFFER.CN
BY 315SOFT.COM
2 代码格式
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
namespace Legalsoft.Truffer.Algorithm
{
public static partial class Algorithm_Gallery
{
/// <summary>
///
/// </summary>
/// <param name="x">数字</param>
/// <param name="p1">位置1</param>
/// <param name="p2">位置2</param>
/// <param name="n">交换字节数目</param>
/// <returns></returns>
public static int Bits_Swap(int x, int p1, int p2, int n)
{
int set1 = (x >> p1) & ((1 << n) - 1);
int set2 = (x >> p2) & ((1 << n) - 1);
int xor = (set1 ^ set2);
xor = (xor << p1) | (xor << p2);
int result = x ^ xor;
return result;
}
public static int Bits_Swap_Second(int x, int p1, int p2, int n)
{
int xor = (int)(((x >> p1) ^ (x >> p2)) & ((1U << n) - 1));
return x ^ ((xor << p1) | (xor << p2));
}
public static int Bits_Swap_Third(int x, int p1, int p2, int n)
{
int shift1, shift2, value1, value2;
while ((n--) > 0)
{
shift1 = 1 << p1;
shift2 = 1 << p2;
value1 = ((x & shift1));
value2 = ((x & shift2));
if ((value1 == 0 && value2 != 0) || (value2 == 0 && value1 != 0))
{
if (value1 != 0)
{
x = x & (~shift1);
x = x | shift2;
}
else
{
x = x & (~shift2);
x = x | shift1;
}
}
p1++;
p2++;
}
return x;
}
}
}