given a number in AX, store the corresponding bit string in str1. if AX = 0x1234, the result should be: str1 = 0001001000111
How can I convert everything in AX to binary Do I have to use loop? How to implement this method?
given a number in AX, store the corresponding bit string in str1. if AX = 0x1234, the result should be: str1 = 0001001000111
How can I convert everything in AX to binary Do I have to use loop? How to implement this method?
Input number in ax
, and output binary string in [rdi]
. If ax = 0x1234
, [rdi] = "0001001000110100"
with a terminating null character.
Using NASM targeting x86_64.
Based on Peter Cordes' post, with hand-tuned scheduling.
movd xmm2, eax
mov rdx, 0x0102040810204080
movq xmm1, rdx
mov edx, 0x30303030
movd xmm0, edx
punpcklbw xmm2, xmm2
punpcklwd xmm2, xmm2
punpckldq xmm2, xmm2
pshufd xmm2, xmm2, 0x4e; swap high64/low64
punpcklqdq xmm1, xmm1; bit-select mask
pand xmm2, xmm1
pcmpeqb xmm1, xmm2
pshufd xmm0, xmm0, 0; "0000..."
psubb xmm0, xmm1
movdqu [rdi], xmm0
mov byte [rdi + 16], 0
Each iteration has no dependency on the previous iteration, and the loop is fully unrolled.
If you are not familiar with NASM macros. Read the docs (https://www.nasm.us/xdoc/2.10rc8/html/nasmdoc4.html).
%assign i 0
%rep 16
xor edx, edx
bt eax, 15 - i
adc edx, 48
mov [rdi + i], dl
%assign i i + 1
%endrep
mov byte [rdi + 16], 0