FORTRAN POPPAR Equivalent in Matlab

1 回表示 (過去 30 日間)
Juan Navarro
Juan Navarro 2021 年 7 月 9 日
編集済み: Juan Navarro 2021 年 7 月 9 日
Hello Matlab comunity, my question is what would be the equivalent to FORTRAN POPPAR function in Matlab?
According to gnc webpage, POPPAR(I) returns parity of the integer I, i.e. the parity of the number of bits set ('1' bits) in the binary representation of I. It is equal to 0 if I has an even number of bits set, and 1 for an odd number of '1' bits.
Thank you!

採用された回答

John D'Errico
John D'Errico 2021 年 7 月 9 日
The obvious answer is the simple answer...
sum(dec2bin(I) - '0')
  1 件のコメント
Juan Navarro
Juan Navarro 2021 年 7 月 9 日
Thank you John!

サインインしてコメントする。

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2021 年 7 月 9 日
bitget() can be faster.
I = randi([0 2^32-1], 1, 1, 'uint32')
I = uint32 1734766993
timeit(@() mod(nnz(dec2bin(I)-'0'),2),0)
ans = 1.1998e-04
timeit(@() fold(@xor, dec2bin(I) - '0', 0), 0)
ans = 5.8975e-05
timeit(@() fold(@xor, bitget(I, 1:32), 0), 0)
ans = 3.8923e-05
timeit(@() mod(sum(bitget(I,1:32)),2),0)
ans = 3.4225e-06
  1 件のコメント
Juan Navarro
Juan Navarro 2021 年 7 月 9 日
編集済み: Juan Navarro 2021 年 7 月 9 日
Thank byou Walter, your help is very much appreciated!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeFortran with MATLAB についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by