使用 C 语言实现全加器
逻辑门电路
与门(AND)
真值表:
| A | B | A AND B | 
|---|---|---|
| 1 | 1 | 1 | 
| 1 | 0 | 0 | 
| 0 | 1 | 0 | 
| 0 | 0 | 0 | 
代码实现:
int AND(int a, int b)
{
    if ((a == 1) && (b == 1))
    {
        return 1;
    }
    return 0;
}
或门(OR)
真值表:
| A | B | A OR B | 
|---|---|---|
| 1 | 1 | 1 | 
| 1 | 0 | 1 | 
| 0 | 1 | 1 | 
| 0 | 0 | 0 | 
代码实现:
int OR(int a, int b)
{
    if ((a == 0) && (b == 0))
    {
        return 0;
    }
    return 1;
}
非门(NOT)
真值表:
| A | NOT A | 
|---|---|
| 1 | 0 | 
| 0 | 1 | 
代码实现:
int NOT(int a)
{
    if (a == 0)
    {
        return 1;
    }
    return 0;
}
异或(XOR)
真值表:
| A | B | A XOR B | 
|---|---|---|
| 1 | 1 | 0 | 
| 1 | 0 | 1 | 
| 0 | 1 | 1 | 
| 0 | 0 | 0 | 
代码实现:
int XOR(int a, int b)
{
    if (a == b)
    {
        return 0;
    }
    return 1;
}
进制转换
十进制转二进制
方法:除二取余,逆序排列
代码实现:
int *binary(int number, int *b)
{
    for (int i = 7; i >= 0; i--)
    {
        b[i] = number % 2;
        number /= 2;
    }
    return b;
}
二进制转十进制
从右往左,第 \(n\) 位如果是 \(1\),则乘上 \(2^{n-1}\),为 \(0\) 则乘 \(0\),最后将值全部相加。
代码实现:
int decimal(int b[])
{
    int output = 0;
    for (int i = 0; i < 8; i++)
    {
        if (b[i] == 1)
        {
            output += pow(2, 7 - i);
        }
    }
    return output;
}
全加器的实现
代码实现:
int FA(int a, int b)
{
    int output = 1;
    int aa[8];
    int *A;
    A = binary(a, aa);
    int bb[8];
    int *B;
    B = binary(b, bb);
    int C[8] = {0};
    C[7] = AND(A[7], B[7]);
    int S[8] = {0};
    for (int i = 6; i >= 0; i--)
    {
        int AxorB = XOR(A[i], B[i]);
        int AB = AND(A[i], B[i]);
        int CAxorB = AND(AxorB, C[i + 1]);
        C[i] = OR(AB, CAxorB);
    }
    for (int i = 7; i >= 0; i--)
    {
        int AxorB = '0' + XOR(A[i], B[i]);
        S[i] = XOR(AxorB, '0' + C[i + 1]);
    }
    output = decimal(S);
    return output;
}

                
            
        
浙公网安备 33010602011771号