• 文章
  • 輔助進位與奇偶校驗檢測器
釋出
2014年6月6日

輔助進位與奇偶校驗檢測器

評分:3.5/5 (51 票)
*****
此程式可用於檢查兩個數字相加時是否會產生輔助進位。這項任務可能很麻煩,因為像 C/C++ 這樣的程式語言雖然在機器級別以二進位制執行,但其在二進位制級別的抽象以及在二進位制級別對一個或多個變數進行操作以確定這些數字的屬性是不可能的。

上述程式在用 C/C++ 等高階程式語言進行二進位制級別操作的構思方面非常有用。此處還必須指出,此程式不相容 C,但基本演算法和實現技術可以保持不變。

這對於那些像我一樣對嵌入式程式設計或嵌入式軟體開發感興趣的人最有幫助,但它仍然可以提供在二進位制級別工作的思路/技術。我建立此程式是為了設計一個微控制器模擬器,該模擬器能夠解釋十六進位制檔案和彙編原始碼,以在軟體級別模擬硬體操作。

主原始檔

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

#include <iostream>
#include <bitset>
#include <string>
#include <sstream>
using namespace std;
bool AC;
bool P;
string dec2bin(int Decimal_Value){
	ostringstream os;
	os<<bitset<8>(Decimal_Value);
	return os.str();
}
void AC_Flag_Update(unsigned char a, unsigned char b){
	string s1 = dec2bin((int)a);
	string s2 = dec2bin((int)b);
	if ( s1.substr(4,1) == "1" && s2.substr(4,1) == "1" )
		AC = true ;
	else if ( s1.substr(4,1) == "0" && s2.substr(4,1) == "0" )
		AC = false;
	else
		AC_Flag_Update(a<<1 , b<<1);

}
void P_Flag_Update(unsigned char a){
	P = false;
	string s = dec2bin((int)a);
	for ( int i = 0; i < s.size(); i++ ){
		if( s.substr(i,1) == "1" )
			P =!P;
	}
}
int main()
{

	unsigned char c = 0x1a;
	unsigned char d = 0x06;
        AC_Flag_Update(c,d);
	P_Flag_Update(d);
	if(AC)
		cout<<"AC is present"<<endl;
	else
		cout<<"NO AC is present"<<endl;
	if(P)
		cout<<"P is SET"<<endl;
	else
		cout<<"P is CLEAR"<<endl;
}


以及 Makefile

1
2
3
4
5
6
7
8
9
10
11

TARGET= main
CC= g++ -std=c++11

all:
	$(CC) -Os -o $(TARGET) $(TARGET).cpp
run: $(TARGET)
	./$(TARGET)
clean:
	rm -f *~ $(TARGET)



AC is present
P is CLEAR