popcnt: Wasm text instruction
Thepopcnt instructions, short forpopulation count, are used to count the amount of1s in a numbers binary representation.
In this article
Try it
(module (func (export "count1s") (param $num i32) (result i32) ;; load the number onto the stack local.get $num ;; count the amount of 1s and return the result i32.popcnt ))const url = "{%wasm-url%}";await WebAssembly.instantiateStreaming(fetch(url), { console }).then( (result) => { const count1s = result.instance.exports.count1s; console.log(count1s(0b10000010)); // Expected output: 2 },);Syntax
wat
;; load a number onto the stacki32.const 130 ;; 10000010;; count the 1si32.popcnt;; the top item on the stack will now be 2| Instruction | Binary opcode |
|---|---|
i32.popcnt | 0x69 |
i64.popcnt | 0x7b |