【发布时间】:2020-07-16 09:46:26
【问题描述】:
我试图在 c# 和 java 中将字符串转换为数值,条件是转换必须相等。 以下 Java - 测试运行:
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import org.junit.Test;
public class JavaTest {
@Test
public void TestJava(){
byte[] bytes = "ABCDEFGH".getBytes(StandardCharsets.UTF_8);
ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
buffer.put(bytes);
long value = buffer.getLong(0);
assertThat(value, is(4702394921427289928L));
}
}
当我尝试在 c# 中使用 BitConverter 转换相同的值时
[Test]
public void TestCSharp()
{
byte[] byteContents = Encoding.UTF8.GetBytes("ABCDEFGH");
long value = BitConverter.ToInt64(byteContents);
Assert.AreEqual(value, 4702394921427289928L);
}
测试是红色的。
有什么办法可以做到吗?有其他选择吗?
编辑: 仅供参考:两个字节数组相等,因此错误必须在从 byte[] 到 long 的转换中
【问题讨论】:
-
你得到了什么价值?你的预期正确吗?
-
这个值对我来说并不重要,只要它在两个实现(c#,java)中是相等的
-
long value = BitConverter.ToInt64(byteContents.Reverse().ToArray(), 0); -
@UlugbekUmirov 介意解释为什么会这样并将其作为答案发布?
-
感谢m8 plz使用答案,所以我可以接受它
标签: c# arrays string long-integer