在 Java 中获取大整数的字符串表示并将其转换为字节数组
基本上,我的问题有两个方面,特别是针对比特币 RPC。我正在用 Java 为 Litecoin(BTC 的衍生产品)编写一个矿工,需要获取一个看起来像这样的字符串:
000000000000000000000000000000000000000000000000000000ffff0f0000
将其转换为如下所示
00000fffff000000000000000000000000000000000000000000000000000000
(我相信这是从小端到大端的切换)
然后我需要将该字符串转换为转换为字节数组——
我查看了 org.apache 中的 Hex 类、String.toByte() 以及一段如下所示的代码:
public static byte[] toByta(char[] data) {
if (data == null) return null;
// ----------
byte[] byts = new byte[data.length * 2];
for (int i = 0; i < data.length; i++)
System.arraycopy(toByta(data[i]), 0, byts, i * 2, 2);
return byts;
}
所以本质上是: 在 Java 中改变字节顺序的最佳方法是什么?获取数字的字符串表示并将其转换为要散列的字节数组的最佳方法是什么?
编辑:更改字节序后我得到了错误的结果。
Basically, my problem is two-fold, and refers pretty specifically to the Bitcoin RPC. I am writing a miner in Java for Litecoin (a spinoff of BTC) and need to take a string that looks like:
000000000000000000000000000000000000000000000000000000ffff0f0000
Convert it to look like
00000fffff000000000000000000000000000000000000000000000000000000
(Which I believe is switching from little endian to big endian)
I then need to turn that string into a byte array --
I've looked at the Hex class from org.apache, String.toByte(), and a piece of code that looks like:
public static byte[] toByta(char[] data) {
if (data == null) return null;
// ----------
byte[] byts = new byte[data.length * 2];
for (int i = 0; i < data.length; i++)
System.arraycopy(toByta(data[i]), 0, byts, i * 2, 2);
return byts;
}
So essentially: What is the best way, in Java to change endianness? And what is the best way to take a string representation of a number and convert it to a byte array to be hashed?
EDIT: I had the wrong result after changing the endian.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你可以获得十六进制字符串。
字符串并调用reverse()。
toString(),然后通过getBytes()获取字节;
不知道这是否是“最好的”,但它几乎不需要您做任何工作。
如果您需要更快的速度,请对原始方向错误的十六进制字符串(来自步骤 1)调用 getBytes() 并使用 for 循环将其反转。例如
you can get the hex String.
String and call reverse().
toString(), then get the bytes via getBytes();
Don't know if this is "best" but it requires little work on your part.
If you need better speed, call getBytes() on the original wrong direction hex string (from step 1) and reverse it in place using a for loop. e.g.