0

While learning C++, i decided to get some knowledge of assembly. So i have to count weight of each byte of some number.

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;


int main()
{
    int x=0;
    int count = 0;
    cout << "Enter number\n";
    cin >> x;
    int z = 8;
    _asm
    {
        mov ebx, z;
        mov eax, x;
        xor ecx, ecx;
    l:
        cmp ebx, 0;
        jne k;
        jmp m;
    k:
        test eax, 11111111;
        shr eax, 1;
        adc ecx, 0;
        dec ebx;
        jmp l;
    m:
        mov count, ecx;
    }
    
    cout << "Counted " << count << " bits";
    return 0;

}

Now it works corret only for 1 byte numbers, how to empower this program for 2 bytes and more?

.......................................

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Nfoth
  • 1
  • 1
    what is the "weight of a byte" ? – 463035818_is_not_an_ai Dec 05 '22 at 11:59
  • `test eax, 11111111` followed by `shr eax, 1` makes the test instruction a no-op. Even if not, the immediate number seems very odd. Did you intend it as a hexadecimal number? – ecm Dec 05 '22 at 12:03
  • 2
    `test eax, 11111111` is useless. Obviously `z` is the number of bits, if you have written this code you should know that. So change that as needed. – Jester Dec 05 '22 at 12:03
  • 1
    @ecm I assume that was meant to be binary to test the least significant byte. – Jester Dec 05 '22 at 12:04
  • 1
    @463035818_is_not_a_number Maybe it's [this thing](https://stackoverflow.com/a/58995487/10871073)? – Adrian Mole Dec 05 '22 at 12:35
  • 1
    Note that C++ already has the tools for this in the [](https://en.cppreference.com/w/cpp/header/bit) header. We don't write much assembly nowadays. – BoP Dec 05 '22 at 13:52
  • Note that `11111111` is a decimal constant, `0xa98ac7`. Did you maybe mean `0xff`? Or `test al,al`? Of course there's no reason to do a `test` here; the `adc` is using the bit shifted out (into CF) by `shr` – Peter Cordes Dec 05 '22 at 14:42
  • Are you looking for separate counts for each byte? Like positional popcount with 8-bit bins? With AVX-512 BITALG, you'd want `vpopcntb` for that. https://www.felixcloutier.com/x86/vpopcnt . Otherwise do the usual SWAR bithack but stop at 8-bit bins. – Peter Cordes Dec 05 '22 at 15:54
  • @463035818_is_not_a_number "Weight" is just another term for "population count" – puppydrum64 Dec 14 '22 at 17:31

0 Answers0