I'm [porting this line from C++ to C#,](https://github.com/bitcoin/bitcoin/blob/master/src/bignum.h#L310) and I'm not an experienced C++ programmer:

```
 unsigned int nSize = BN_num_bytes(this); 

```

In .NET I'm [using System.Numerics.BigInteger](https://bitcoin.stackexchange.com/q/8100/1878) 

```
 BigInteger num = originalBigNumber;
 byte[] numAsBytes = num.ToByteArray();
 uint compactBitsRepresentation = 0;
 uint size2 = (uint)numAsBytes.Length;

```

I think there is a fundamental difference in how they operate internally, since [the sources' unit tests' results](https://bitcoin.stackexchange.com/a/8046/1878) don't match if the BigInt equals:

* 0
* Any negative number
* 0x00123456

I know literally nothing about `BN_num_bytes` (*edit: the comments just told me that it's a macro for BN\_num\_bits)*. 

**Question**

Would you verify these guesses about the code:

* I need to port `BN_num_bytes` which is a macro for `((BN_num_bits(bn)+7)/8)` (Thank you @WhozCraig)
* I need to port `BN_num_bits` which is `floor(log2(w))+1`

Then, if the possibility exists that leading and trailing bytes aren't counted, then what happens on Big/Little endian machines? Does it matter?

Based on [these answers on Security.StackExchange,](https://security.stackexchange.com/a/31979/396) and that my application isn't performance critical, I may use the default implementation in .NET and not use an alternate library that may already implement a comparable workaround.

---

Edit: so far my implementation looks something like this, but I'm not sure what the "LookupTable" is as mentioned in the comments.

```
   private static int BN_num_bytes(byte[] numAsBytes)
    {
        int bits = BN_num_bits(numAsBytes);
        return (bits + 7) / 8; 
    }

    private static int BN_num_bits(byte[] numAsBytes)
    {
        var log2 = Math.Log(numAsBytes.Length, 2);
        var floor = Math.Floor(log2);
        return (uint)floor + 1;
    }

```

---

Edit 2:

After some more searching, [I found that:](https://groups.google.com/forum/?fromgroups=#!topic/mailing.unix.openssh-dev/DDGOu6w9_7c)

> 
> BN\_num\_bits does not return the number of significant bits of a given bignum, but rather the position of the most significant 1 bit, which is not necessarily the same thing
> 
> 
> 

Though I still don't know what the source of it looks like...