vak: (Аристипп)
[personal profile] vak
Это такие специальные коаны для программистов.
Кто осознает глубокий смысл каждого фрагмента, достигнет нирваны.

Date: 2026-02-25 21:09 (UTC)
spamsink: (Default)
From: [personal profile] spamsink
Да уж, прошли те времена, когда подобного эффекта можно было достигнуть на микрокалькуляторе Б3-18 с помощью 1+=⟷=⟷=⟷=...

Date: 2026-02-25 22:17 (UTC)
spamsink: (Default)
From: [personal profile] spamsink
На Rockwell трюк работает?

Date: 2026-02-25 22:29 (UTC)
spamsink: (Default)
From: [personal profile] spamsink

Cursor в состоянии достичь нирваны:

What does the sequence of x86 instructions "neg rax; sbb rax,rax; neg rax" do?

This instruction sequence is a clever branchless way to convert a value to a boolean (0 or 1):
Step-by-step breakdown:
1. neg rax - Negates rax (two's complement)
• If rax == 0: result is 0, carry flag CF = 0
• If rax != 0: result is -rax, carry flag CF = 1
2. sbb rax, rax - Subtract with borrow: rax = rax - rax - CF
• If CF == 0: rax = 0 - 0 - 0 = 0
• If CF == 1: rax = 0 - 0 - 1 = -1 (0xFFFFFFFFFFFFFFFF)
3. neg rax - Negates rax again
• If rax == 0: result is 0
• If rax == -1: result is 1

Overall effect:
• Input rax == 0 → Output rax = 0
• Input rax != 0 → Output rax = 1

This is essentially computing rax = (rax != 0) ? 1 : 0 without any branches. It's a classic trick used in performance-critical code where branch mispredictions would be costly, converting any non-zero value to exactly 1.

What does the sequence of x86 instructions ".loop: xadd rax,rdx; loop .loop" do?

This instruction sequence computes Fibonacci numbers (or a Fibonacci-like recurrence):
Breakdown:
1. xadd rax, rdx - Atomic exchange-and-add:
• Saves old rax to a temp location
• rax = rax + rdx
• rdx = temp (old value of rax)
2. loop .loop - Decrements rcx and jumps to .loop if rcx != 0

What it does:
Starting with initial values rax = A, rdx = B, rcx = N:
• Iteration 1: rax = A+B, rdx = A
• Iteration 2: rax = (A+B)+A = 2A+B, rdx = A+B
• Iteration 3: rax = (2A+B)+(A+B) = 3A+2B, rdx = 2A+B
• Iteration 4: rax = 5A+3B, rdx = 3A+2B

The coefficients follow the Fibonacci sequence!
Classic use case:
mov rax, 1; mov rdx, 0; mov rcx, N; .loop: xadd rax, rdx; loop .loop After N iterations:
• rax = F(N+2) (the (N+2)th Fibonacci number)
• rdx = F(N+1) (the (N+1)th Fibonacci number)

This is a compact, branchless way to compute Fibonacci numbers, though the loop instruction itself is somewhat slow on modern
processors, so it's more of a code golf trick than production code.