c#BigInteger到32字节的十六进制

问题描述 投票:0回答:1

我需要从biginteger变为32字节的十六进制值。要在此说明的第三个参数中使用:

getwWork documentation

我当前的代码未生成有效的十六进制值。

public static string GetTargetHex(BigInteger difficulty)
{
    // 2^256 / difficulty.
    var target = BigInteger.Divide(BigInteger.Pow(2, 256), difficulty);
    return $"0x{target.ToString("X16").ToLower()}";
}

[我现在只需要知道23142114022743的值会导致十六进制值为'0x00000000000c29b321174712bb7ca6dd0896b050e18d4c7e13df4c1aee84f2c0'。

c# hex biginteger ethereum
1个回答
0
投票

以太坊有自己的十六进制编码/解码标准。

您可以为此使用Nethereum。

从屏幕快照开始工作:

using System;
using System.Text;
using Nethereum.Hex.HexConvertors.Extensions;
using System.Threading.Tasks;
using Nethereum.Web3;
using Nethereum.RPC.Eth.Blocks;
using Nethereum.Hex.HexTypes;

public class HexDecoding
{
    private static async Task Main(string[] args)
    {
        var web3 = new Web3("your url");
        var work = await web3.Eth.Mining.GetWork.SendRequestAsync();
                Console.WriteLine(work.Length);
    }
}

并进行计算,根据您的字节序,您可以执行以下操作:

using System;
using System.Text;
using Nethereum.Hex.HexConvertors.Extensions;
using System.Threading.Tasks;
using Nethereum.Web3;
using Nethereum.RPC.Eth.Blocks;
using Nethereum.Hex.HexTypes;
using System.Numerics;

public class HexDecoding
{
    private static async Task Main(string[] args)
    {
         var difficulty = 23142114022743;
         var target = BigInteger.Divide(BigInteger.Pow(2, 256), difficulty);
         Console.WriteLine(target);


        // A simple check on endianism and reversing
        byte[] bytes;
        Console.WriteLine(BitConverter.IsLittleEndian);
        if (BitConverter.IsLittleEndian) 
                bytes = target.ToByteArray().Reverse().ToArray();
            else
                bytes = target.ToByteArray().ToArray();

        Console.WriteLine(bytes.ToHex());


         //Another option using .Net core now (awesome)
        Console.WriteLine(target.ToByteArray(true, true).ToHex()); // new .net core 

         //Final option if you are using Nethereum and not using .Net core
        Console.WriteLine(HexBigIntegerConvertorExtensions.ToByteArray(target, false).ToHex()); 
                //0x00000000000c29b321174712bb7ca6dd0896b050e18d4c7e13df4c1aee84f2c0

                //0x00000000000c29b321174712bb7ca6dd0896b050e18d4c7e13df4c1aee84f2c0
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.