gpt4 book ai didi

C#:无法从 ulong 转换为 byte

转载 作者:行者123 更新时间:2023-11-30 18:54:29 25 4
gpt4 key购买 nike

很奇怪我怎么能在 C++ 中做到这一点,但在 C# 中却不行。

为了清楚起见,我将在 C++ 中粘贴这两个函数,然后在 C# 中粘贴,并在 C# 代码中用注释“//error”标记有问题的行。这两个函数所做的是对参数进行编码,然后将其添加到名为 byte1seeds 的全局变量中。

这些是C++中的函数

//Global var:

unsigned char byte1seeds[3];

unsigned long GenerateValue( unsigned long * Ptr )
{
unsigned long val = *Ptr;
for( int i = 0; i < 32; i++ )
val = (((((((((((val >> 2)^val) >> 2)^val) >> 1)^val) >> 1)^val) >> 1)^val)&1)|((((val&1) << 31)|(val >> 1))&0xFFFFFFFE);
return ( *Ptr = val );
}

void SetupCountByte( unsigned long seed )
{
if( seed == 0 ) seed = 0x9ABFB3B6;
unsigned long mut = seed;
unsigned long mut1 = GenerateValue( &mut );
unsigned long mut2 = GenerateValue( &mut );
unsigned long mut3 = GenerateValue( &mut );
GenerateValue( &mut );
unsigned char byte1 = (mut&0xFF)^(mut3&0xFF);
unsigned char byte2 = (mut1&0xFF)^(mut2&0xFF);
if( !byte1 ) byte1 = 1;
if( !byte2 ) byte2 = 1;
byte1seeds[0] = byte1^byte2;
byte1seeds[1] = byte2;
byte1seeds[2] = byte1;
}

现在是 C# 代码:

我已经更改了函数 GenerateValue。它没有将指针作为参数,而是使用了一个 ulong 参数。

要调用它并更改我使用的两个值:

  1. ulong mut1 = GenerateValue(mut);
  2. mut = mut1;

下面是翻译后的函数(有问题的行用"//error"标记);

//Global var:
public static byte[] byte1seeds = new byte[3];

public static ulong GenerateValue(ulong val)
{
for( int i = 0; i < 32; i++ )
val = (((((((((((val >> 2)^val) >> 2)^val) >> 1)^val) >> 1)^val) >> 1)^val)&1)|((((val&1) << 31)|(val >> 1))&0xFFFFFFFE);
return val ;
}

public static void SetupCountByte( uint seed )
{
if( seed == 0 ) seed = 0x9ABFB3B6;
ulong mut = seed;
ulong mut1 = GenerateValue(mut);
mut = mut1;
ulong mut2 = GenerateValue(mut);
mut = mut2;
ulong mut3 = GenerateValue(mut);
mut = mut3;
mut = GenerateValue(mut);
byte byte1 = (mut & 0xFF) ^ (mut3 & 0xFF); //error
byte byte2 = (mut1 & 0xFF) ^ (mut2 & 0xFF); //error
if( byte1 != 0 )
byte1 = 1;
if( byte2 != 0 )
byte2 = 1;
byte1seeds[0] = byte1^byte2; //error
byte1seeds[1] = byte2;
byte1seeds[2] = byte1;
}

错误是:

无法将类型“ulong”隐式转换为“byte”。存在显式转换(是否缺少强制转换?)

编辑:有问题的第 3 行的错误是:

无法将类型“int”隐式转换为“byte”。存在显式转换(是否缺少强制转换?)

问题来了:如何解决这些错误?

提前致谢!

最佳答案

添加一个 (byte) 来转换它。由于您可能会失去精度,因此您必须告诉编译器该值将适合一个字节,即

byte byte1 = (byte)((mut & 0xFF) ^ (mut3 & 0xFF));
byte byte2 = (byte)((mut1 & 0xFF) ^ (mut2 & 0xFF));

关于C#:无法从 ulong 转换为 byte,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/685738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com