我知道在java中,您可以通过使用long.reverse(100000001010101)简单地反转long(101010100000001)。但是,c# 中是否存在类似的东西?
你的问题的答案是否定的。 然而它可以通过代码来实现。 这个怎么样...
public static long RevLong(long l)
{
long tmp = l;
long r = 0L;
if (tmp < 0)
tmp *= -1;
while (tmp > 0)
{
r = (r * 10) + (tmp - ((tmp / 10)) * 10);
tmp = tmp / 10;
}
return r * (l < 0 ? -1 : 1);
}
怎么样...
public ulong Bit(ulong x, int n)
{
return (x & (1 << n)) >> n;
}
public ulong ReverseBits(ulong x)
{
ulong result = 0;
for (int i = 0; i < 64; i++)
result = result | (x.Bit(64 - i) << i);
return result;
}
反转长的另一种方法是:
long num = 123456789;
long reversed = 0;
while (num > 0)
{
reversed = (reversed * 10) + (num % 10);
num /= 10;
}
或
long num = 123456789;
long reversed = 0;
while (num > 0)
{
reversed = (reversed << 1) + (reversed << 3) + (num & 1);
num >>= 1;
}
或
public static long ReverseBits(long number)
{
long result = 0;
const int numbersOfBitsInLong = sizeof(long) * 8; //Could be set to 64
for (var i = 0; i < numbersOfBitsInLong; i++)
{
result <<= 1;
result |= number & 1;
number >>= 1;
}
return result;
}
最初的问题要求反转二进制位,而不是十进制数字。下面将对 uint 中的位执行按位反转。要将其更改为 ulong: s/uint/ulong/g s/31/63/g s/32/64/g
// Reverse the bits in a uint
uint ReverseBits(uint x)
{
uint ret = 0;
uint maskI = (uint)1; // lsb
uint maskO = (uint)1 << 31; // msb
for (int i = 0; i < 32; i++)
{
// If the specified bit is set, then set the corresponding bit in the return result.
if ((x & maskI) != 0)
ret |= maskO;
maskI = maskI << 1;
maskO = maskO >> 1;
}
return ret;
}
这里有一些有趣的例子。 您可以将其中之一改编为扩展方法,如下所示:
public static class LongExtension
{
public static ulong Reverse(this ulong value)
{
return (value & 0x00000000000000FFUL) << 56 | (value & 0x000000000000FF00UL) << 40 |
(value & 0x0000000000FF0000UL) << 24 | (value & 0x00000000FF000000UL) << 8 |
(value & 0x000000FF00000000UL) >> 8 | (value & 0x0000FF0000000000UL) >> 24 |
(value & 0x00FF000000000000UL) >> 40 | (value & 0xFF00000000000000UL) >> 56;
}
}
然后你可以这样称呼它:
ulong myLong = 3L;
ulong reversed = myLong.Reverse();
string s = 101010100000001.tostring();
char[] charArray = s.ToCharArray();
Array.Reverse( charArray );
return new string( charArray );