// Binary division implementation


// Performs division on two 8 bit unsigned bytes
// Returns dividend/divisor.
// If remainder is non-null it will be set to the remainder.
// Implemented using simple binary division
byte div8u(byte dividend, byte divisor, byte* remainder) {
    byte rem = 0;
    byte quotient = 0;
    for( byte i : 0..7) {
        rem = rem << 1;
        if( (dividend & $80) != 0 ) {
            rem++;
        }
        dividend = dividend << 1;
        quotient = quotient << 1;
        if(rem>=divisor) {
            quotient++;
            rem = rem - divisor;
        }
    }
    *remainder = rem;
    return quotient;
}

word rem16u = 0;

// Performs division on two 16 bit unsigned bytes
// Returns dividend/divisor.
// The remainder will be set into the global variable rem16u
// Implemented using simple binary division
word div16u(word dividend, word divisor) {
    word rem = 0;
    word quotient = 0;
    for( byte i : 0..15) {
        rem = rem << 1;
        if( (>dividend & $80) != 0 ) {
            rem++;
        }
        dividend = dividend << 1;
        quotient = quotient << 1;
        if(rem>=divisor) {
            quotient++;
            rem = rem - divisor;
        }
    }
    rem16u = rem;
    return quotient;
}