1

I need to take a numeric input which is greater than 64 bits, ensure only the remaining 83 bits (if input is greater than 83 bit) are discarded and convert it into a hex string.

I have found I can use BigInteger (System.Numerics.BigInteger) to accept the numeric input from the user but I am unsure how to proceed with this. I have outlined my approach below:

BigInteger myBigInteger = BigInteger.Parse("123456789012345678912345");
 byte[] myByte = myBigInteger.ToByteArray();
 if (myByte.Length < 11) // if input is less than 80 bits
 {
    // Convert Endianness to Big Endian 
    // Convert myBigInteger to hex and output
 }
 // Drop the elements greater than 11
 // Convert element 10 to int and & it with 0x7F
 // Replace the element in the array with the masked value
 // Reverse array to obtain Big Endian
 // Convert array into a hex string and output

I am not sure what I have in mind is the correct approach to solve this problem. Any advice would be appreciated.

Thanks.

MrR0b0t
  • 57
  • 5

1 Answers1

1

Cheat! :-)

public static readonly BigInteger mask = new BigInteger(new byte[]
{
    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
    0xFF, 0xFF, 0x07
});

static void Main(string[] args)
{
    BigInteger myBigInteger = BigInteger.Parse("1234567890123456789123450000");
    BigInteger bi2 = myBigInteger & mask;

    string str = bi2.ToString("X");

Use the bitwise & to truncate your number with a pre-calculated mask! Then use .ToString("X") to write it in hex form.

Note that if you need exactly 83 bits, then it is 10 blocks of 8 bits plus 3 bits... the last 3 bits are 0x07 not 0x7F!

Note that you can:

string str = bi2.ToString("X21");

to have the number padded to 21 digits (as the greatest hex number that can be represented in 83 bits)

xanatos
  • 109,618
  • 12
  • 197
  • 280
  • 2
    Alternatively: `BigInteger mask = BigInteger.Parse("7FFFFFFFFFFFFFFFF", NumberStyles.AllowHexSpecifier);`. – Rudy Velthuis Jun 22 '18 at 16:11
  • @d1d3k Because you were trying to use the "direct" way, I used lateral thinking. So in a way I've cheated against the straight reasoning... Or was mine the straight way and yours the lateral thinking? Mmmmh... Perhaps after seeing your `ToByteArray()` I considered it to be the "main road" and mine to be the sideroad but I was wrong. – xanatos Jun 25 '18 at 07:30