Skip to content

Instantly share code, notes, and snippets.

@trvswgnr
Created April 19, 2024 06:48
Show Gist options
  • Save trvswgnr/b855662b7947be9424853831f576e3dc to your computer and use it in GitHub Desktop.
Save trvswgnr/b855662b7947be9424853831f576e3dc to your computer and use it in GitHub Desktop.
sub and add repr in c
#include <stdio.h>
#include <stdint.h>
uint8_t da(uint8_t value) {
uint8_t lo = value & 0x0F;
uint8_t hi = value >> 4;
if (lo > 9) lo += 6;
if (hi > 9) hi += 6;
return (hi << 4) | lo;
}
void subtract(uint8_t* R0, uint8_t* R1, uint8_t* DPTR) {
uint8_t R7 = 0x03; // loop counter set to 3 so that we can process 4 bytes
uint8_t A; // acc for ops
for (; R7 > 0; R7--) {
uint8_t PSW = 0; // simulating psw here, assuming it includes carry flag
PSW &= ~0x01; // clear carry flag
A = 0x99; // set acc to 0x99
// subtract with borrow
if (PSW & 0x01) { // check if carry is set
A = A - *R1 - 1; // if it is, subtract 1 from the result
} else {
A = A - *R1; // if not, just subtract
}
// restore carry flag
PSW |= (A > 0x99) ? 0x01 : 0x00;
// add with carry
if (PSW & 0x01) {
A = A + *R0 + 1; // if carry is set, add 1 to the result
} else {
A = A + *R0; // if not, just add
}
// decimal adjust (assuming adjusts acc for bcd)
A = da(A); // placeholder for decimal adjust operation
// store result and increment pointers
*DPTR = A;
DPTR++;
R1++;
R0++;
}
}
int main() {
uint8_t dataX[4] = {0x03, 0x01, 0x07, 0x04};
uint8_t dataY[4] = {0x02, 0x05, 0x03, 0x06};
uint8_t results[4] = {0}; // to store results
subtract(dataX, dataY, results);
printf("results:\n");
for (int i = 0; i < 4; i++) {
printf("result[%d] = %02X\n", i, results[i]);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment