Search code examples
c++ntl

NTL - how to get the integer representation of an element in GF(2^n)


Is there a way to get the integer representation of that vector of coefficients? i.e. in a way that the highest degree coefficient is the MSB of that integer and the coefficient of x^0 is the LSB? when using the method BytesFromGF2X it results in a weird representation which is neither big endian nor little endian.

For example, if the element is x^23+x^20+x+1 then I would like to get the integer: 2^23+2^20+2+1.


Solution

  • Use these two methods to convert back and forth to a little endian integer representation:

    FROM GF2X TO LITTLE ENDIAN INTEGER

    void MyBytesFromGF2X(unsigned char* buffer, NTL::GF2X& p, int numbytes) {
        int degree = NTL::deg(p);
        memset(buffer,0,numbytes);
        for(int i=0; i<=degree; i++) {
            if(NTL::IsOne(NTL::coeff(p,i))) {
                buffer[i/8] |= 1 << i%8;
            }
        }
    }
    

    At the end buffer contains the number represented by p in a normal little-endian fashion.

    If you want to get the integer, then assume that the maximum degree of p is 32 then you do the following:

    USAGE

    unsigned char buffer[4];
    int *integer = buffer;
    NTL::GF2X p;
    NTL::SetCoeff(p,1,1); // set the coefficient of x^1 to 1
    NTL::SetCoeff(p,30,1); // set the coefficient of x^30 to 1
    MyBytesFromGF2X(buffer,p,4);
    printf("%d",integer);
    //result will be LE integer representation of 2^30+2^1
    

    In order to convert back to GF2X you ca use this:

    FROM LITTLE ENDIAN INTEGER TO GF2X

    void MyBytesToGF2X(const unsigned char* buffer, NTL::GF2X& p, int numbytes) {
        for(int i=0; i<numbytes; i++) {
            for(int j=0; j<8; j++) {
                int bit = (buffer[i]>>j)&1;
                NTL::SetCoeff(p, i*8+j, bit);
            }
        }
    }