首页 > 解决方案 > c++ (u256)*(h256 const*)(char*[] + int) 强制转换重写为java

问题描述

我需要将一些代码从 c++ 重写为 java,我遇到了这样的 c++ 代码的麻烦:

using u256 = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<256, 256, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void>>;
using h256 = FixedHash<32>;
using bytes = std::vector<byte>;

uint32_t offset = ...;
bytes m_data = ...;
u256 result;
result = (u256)*(h256 const*)(m_data.data() + (size_t)offset);

我不知道发生了什么以及如何用java代码重写它。我了解到,首先我们制作并偏移,现在指向 m_data 数组的某个元素,然后转换为 h256 类型的数组(我看过调试,这个转换做了以下内容:我们从 0 获取数据到从 m_data 偏移然后转换为 32 大小的数组,前导零)然后我们得到这个数组的第一个值(我不确定)并转换为 u256?但是 (h256 const*) 强制转换后的第一个值为零,但无论如何结果值不是零。你有什么想法吗?

标签: javac++casting

解决方案


我不知道 u256 是什么,问题错过了 typedef,但这是 C 中从内存中的缓冲区获取标量类型(int16_t、int32_t、int64_t、double ....)的典型方法。

本质上是语法的使用:

type t = (type)*(const type *)(buffer + offset)

...让您从特定索引开始的字节数组中获取特定类型的对象。

它不是很安全,但转换为组装时速度很快!

注意:指针数学取决于“buffer”的声明,如果它是 int8_t * 例如缓冲区将从“offset”-nth 字节获取,如果它是 int32_t * 它将从“offset * 4”-nth 使用字节。


推荐阅读