Previous post need some corrections... I'm writing test program ATM, errors will be fixed later.
EDIT: fixed ALU SUM errors and wrote test program:
Code:
#include <stdio.h>
int nand (int a, int b, int bit )
{
int bit_a = (a >> bit) & 1;
int bit_b = (b >> bit) & 1;
return (~ (bit_a & bit_b)) & 1;
}
int nor (int a, int b, int bit )
{
int bit_a = (a >> bit) & 1;
int bit_b = (b >> bit) & 1;
return (~ (bit_a | bit_b)) & 1;
}
int noteor (int a, int b, int bit )
{
return ~ (~nor(a,b,bit) & nand(a,b,bit));
}
int eor (int a, int b, int bit )
{
return ~ (~nand(a,b,bit) | nor(a,b,bit));
}
int alusum ( int a, int b, int carry_in, int *carry, int numbits )
{
int bit;
int carry_out = ~carry_in;
int sum = 0, s;
for (bit=0; bit<numbits; bit++)
{
if ( bit & 1 ) {
carry_in = carry_out & 1;
carry_out = ~(~nor(a,b,bit) & carry_in) & nand(a,b,bit);
s = ~(eor(a,b,bit) & ~carry_in) & (eor(a,b,bit) | ~carry_in);
}
else {
carry_in = carry_out & 1;
carry_out = ~(nand(a,b,bit) & carry_in) & ~nor(a,b,bit);
s = ~(noteor(a,b,bit) & ~carry_in) & (noteor(a,b,bit) | ~carry_in);
}
//printf ( "%i: %i %i %i %i %i\n", bit, (a >> bit) & 1, (b >> bit) & 1, s & 1, carry_in & 1, carry_out & 1);
sum |= (s & 1) << bit;
}
*carry = ~carry_out & 1;
return ~sum & ((1 << numbits) - 1);
}
void logic_test ( int a, int b )
{
int bit;
for (bit=0; bit<8; bit++)
{
printf ( "NAND=%i ", nand(a, b, bit) );
printf ( "NOR=%i ", nor(a, b, bit) );
printf ( "EOR=%i \n", eor(a, b, bit) );
printf ( "!EOR=%i \n", noteor(a, b, bit) );
}
}
main ()
{
int a, b, sum, carry;
//logic_test ( 0x35, 0x53 );
printf ( "6502 ALU test.\n" );
printf ( " A B S C\n" );
for ( a=0; a<256; a++ )
{
for (b=0; b<256; b++)
{
sum = alusum ( a, b, 0, &carry, 8 );
printf ( "%02X %02X %02X %01X\n", a, b, sum, carry );
}
}
}
Now everything is correct.
Code:
6502 ALU test.
A B S C
03 F9 FC 0
03 FA FD 0
03 FB FE 0
03 FC FF 0
03 FD 00 1
03 FE 01 1
03 FF 02 1
04 00 04 0
04 01 05 0
BCD correction is next.