Search code examples
carrayscharbit-manipulationbitwise-operators

Substract an char array minus int in C


I have a char array:

char message[];

And an 8-bit integer

uint8_t remainder

I want to treat both just as arrays of bits and subtract them like:

message - remainder

and treat the result as a char array:

An example would be

char* message = "ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ";
// Equivalent to a 512-bit array of only 1s

uint8_t remainder = 1;
// Substract here message-remainder

printf("%s", message)
// Output: "ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿþ"
// As the 512 bit array would still be just 1s except for the first bit which now is 0, so the first char would be 254 instead of 255

Is there a possible way to do it? I thought about converting the char array to an int but the problem is that it usually is a 64 byte array, so I cannot treat is an int. I think the approach goes around using bitwise operators but I haven't figured how to subtract them yet.

Any suggestions?


Solution

  • As requested:

    1. Read from the byte array (chars) as a type-casted integer. Beware that endian may cause this to not work correctly on some systems and you may have to endian swap. Also beware that if the data is not aligned to word boundaries, some systems may crash.
    2. Compare your remainder vs the integer. If integer >= remainder, there is no carry and you can just subtract the values and typecast store the integer back into the char array. Same exceptions apply as stated above.
    3. If remainder is bigger, still do the subtract and store, but then place a 1 into remainder.
    4. Loop back to 1, reading in next word until you exit because of no carry to propagate or out of words to read.

    If data is non-aligned, not size of word, etc., you may need to do this per byte instead, but you have stated this is not the case.

    Enjoy.

    (Note: Using a BigNum type library is highly recommended over doing it yourself. Someday, this code may need to be ported, and this method is highly likely to break when that occurs...)