Modular algorithm with byte array and 8-bit integer: 8bit = bytes% 8bit

I need to create an algorithm implemented in C that performs modulo arithmetic between an arbitrary number of bytes and one byte. See this:

typedef struct{
    u_int8_t * data;
    u_int16_t length;
}UBigInt;
u_int8_t UBigIntModuloWithUInt8(UBigInt a,u_int8_t b){

}

For powers of two, a and (b-1) can be used, but what about non-powers of two?

I understand that one of the methods is: a - b * (a / b)

This will require the use of UBigIntDivisionWithUInt8 and UBigIntMultiplicationWithUInt8 and UBigIntSubtractionWithUBigInt. Maybe a more efficient way to do this?

Thank.

This is the implementation I have now:

u_int8_t UBigIntModuloWithUInt8(UBigInt a,u_int8_t b){
    if (!(b & (b - 1)))
        return a.data[a.length - 1] & b - 1; // For powers of two this can be done
    // Wasn't a power of two.
    u_int16_t result = 0; // Prevents overflow in calculations
    for(int x = 0; x < a.length; x++) {
        result *= (256 % b);
        result %= b;
        result += a.data[x] % b;
        result %= b;
    }
    return result;
}
+3
source share
1 answer

.
:
a % b = ((a // 256) % b) * (256 % b) + (a % 256) % b, x//y - ( C ). , b . O(length) O(log(a)).
(, C ):

u_int16_t result = 0; // Just in case, to prevent overflow
for(i = 0, i<a.length; i++) {
    result *= (256 % b);
    result %= b;
    result += (a[i] % b);
    result %= b;
}

: a = (a // 256) * 256 + (a % 256), a % b = ((a // 256) * 256) % b + ((a % 256) % b). a % 256 = a[n-1] a // 256 = a[0 .. n-2]. .

+4

All Articles