首页 > 解决方案 > 如何将 bool 数组(0 或 1 字节)转换为二进制整数?

问题描述

请帮助如何通过二进制数组(数组的值在程序中填写)并分配总变量值total = total * 2 + digit(数字是数组中的二进制数字),循环完成后,变量total的输出值在控制台中并在 masm32 中执行?

array = [1, 1];
let total = 0;
for (let i = 0; i < length_of_array; i++){
 
total = total * 2 + array[i];
 
}
 
print(total); // 3

标签: assemblyx86masmmasm32

解决方案


您可以编写以下代码:

.386
.model flat, stdcall
.stack 1000h

include \masm32\include\masm32rt.inc

.data
array db 1, 1 ; defining the array
arrlength db 2 ; array length

consoleOutHandle dd ? 
bytesWritten dd ? 
message db "------",13,10
lmessage dd 8 ; print declarations

.code
main proc

    mov ebx, offset array ; array location
    mov eax, 0 ; total
    mov ecx, 0 ; i
    loopLabel:
        push ecx
        mov ecx, 2
        mov edx, 0
        mul ecx ; eax = eax * 2
        pop ecx
        add ebx, ecx ; ebx is pointing to array[i]
        add al, byte ptr [ebx]
        sub ebx, ecx ; resetting ebx
        inc ecx
        cmp cl, byte ptr [arrlength] ; checking if i is bigger or equal to the length
    jb loopLabel
    ; the print section
    invoke dwtoa, eax, offset message
    INVOKE GetStdHandle, STD_OUTPUT_HANDLE
    mov consoleOutHandle, eax 
    mov edx,offset message 
    pushad    
    mov eax, offset message
    INVOKE WriteConsoleA, consoleOutHandle, edx, eax, offset bytesWritten, 0
    popad

    invoke ExitProcess, 0
main endp

end main
; 00F9FC60

这可行,但根据您运行它的环境,您可能需要更改打印部分以以不同的方式运行。


推荐阅读