使用LC3模拟器计算二进制数中的1的数量

时间:2016-10-05 05:35:16

标签: assembly binary hex bitmask lc3

我正在尝试为LC3模拟器编写一个程序,它允许我计算存储在内存中其他位置的二进制数的1的数量。以下是我到目前为止的情况:

0011 0001 0000 0000   ; Start the data at memory location x3100
0110 1010 1111 0001   ; Hex number stored at x3000

0011 0000 0000 0000   ; Start the program at x3000
0101 001 001 1 00000  ; Clear R1 (Contain address of number)
0101 010 010 1 00000  ; Clear R2 (Counter for amount of 1's)
0001 011 011 1 00001  ; Load R3 with 1 (Number for 'and-ing' with number getting checked)
;^cant do this line since that is a decimal 1 not binary one therefore it wouldnt left shift
; and cant store and get a binary number in memory

0001 100 100 1 01111  ; Load R4 with 16 (Loop loops til 0)
1110 001 011111100    ; Load R1 with address of number
0110 101 001 000000   ; Load R5 with the number stored at x3100
0101 110 101 000 011  ; And R3 with R5 store result in R6
                      ; If number is not zero, increment R2 by 1
0001 011 011 000 011  ; Add R3 with itself to make a left shift
0001 100 100 1 11111  ; Decrement R4 by 1
                      ; Loop to x3006 (When R3 is 'And-ed' with R5) if R4 isnt 0
0011 010 011111101    ; Store value from R2 in x3101
1111 0000 00100101    ; Halt (Is this correct?) set breakpoint here

我很困惑如何制作一个“if语句”来检查某些值,以及如果不满足条件,如何循环回某个点。关于如何实际计算1的数量的思考过程是和原始二进制数用“0000000000000001”检查,如果结果值不是0然后将1添加到我的“1的计数器”然后左移1值到检查原始号码中的下一个值。我注意到我无法做某一行,因为我相信我在寄存器3中存储了一个十进制1,而不是二进制1,并且无法将它移位。我的一个限制是我不能使用内存中的任何其他位置而不是x3100和x3101来存储原始数字并分别存储1的数量。

我听说有点掩码会非常有用,但我搜索了高低,无法找到如何使用它。任何帮助将不胜感激,谢谢!

1 个答案:

答案 0 :(得分:0)

这是我的代码,它计算存储在R6中的1,默认情况下我用x7562填充。使用分支和标签来处理子例程。 ##

.ORIG x3000 ;start point

;R6 is the the register of number stored
;R1 is the register for manipulation of the number stored
;R2 is the counter for number of 1s
;R3 is the bitmask
;R4 is the loopcounter
;R5 is the storage for AND operation

AND R1,R1,#0; Clean R1
AND R2,R2,#0; Clean R2
AND R3,R3,#0; Clean R3
AND R4,R4,#0; Clean R4
AND R5,R5,#0; Clean R5

ADD R3,R3,#1; Set the value of R3 to 1
ADD R4,R4,#15; Set the loop counter to 15

LD  R6,FILL_R6
ADD R1,R6,#0;

CHECK  AND  R5,R3,R1;
       BRz  #1;
       ADD  R2,R2,#1;
       ADD  R3,R3,R3; Left shift bitmask
       ADD  R4,R4,#-1
       BRzp CHECK

STI R2,STORE_x5000

FILL_R6     .FILL X756
STORE_x5000 .FILL x5000

.END