rust


Why does my Hamming weight function work in C but not in Rust?


I've got the following Hamming weight code in Rust, and it returns garbage for 0xffff and 0xffffffff, but the identical code in C works, so I must be misunderstanding something about how Rust does bit-level operations. It's completely parenthesized, so I don't think it's an operator-precedence issue.
In C:
#include <stdio.h>
int hamming_weight(int val) {
int v1 = val - ((val >> 1) & 0x55555555);
int v2 = (v1 & 0x33333333) + ((v1 >> 2) & 0x33333333);
return (((v2 + (v2 >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24;
}
int main() {
printf("%x -> %d\n", 7, hamming_weight(7));
printf("%x -> %d\n", 0xff, hamming_weight(0xff));
printf("%x -> %d\n", 0xffff, hamming_weight(0xffff));
printf("%x -> %d\n", 0xffffffff, hamming_weight(0xffffffff));
return 0;
}
The results:
7 -> 3
ff -> 8
ffff -> 16
ffffffff -> 32
In Rust (I had to use u64 to prevent overflow panics on 0xffff):
fn hamming_weight(val: u64) -> u64 {
let v1 = val - ((val >> 1) & 0x55555555);
let v2 = (v1 & 0x33333333) + ((v1 >> 2) & 0x33333333);
(((v2 + (v2 >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24
}
fn main() {
println!("{:x} {}", 7, hamming_weight(7));
println!("{:x} {}", 0xff, hamming_weight(0xff));
println!("{:x} {}", 0xffff, hamming_weight(0xffff));
println!("{:x} {}", 0xffffffffu32, hamming_weight(0xffffffffu64));
}
The results:
7 3
ff 8
ffff 2064
ffffffff 135272480
I'm using Rust 1.16. I know Rust has count_ones() - the compiler told me when I was writing this code, which was pretty amazing, but I am choosing to not use it.
I had to use u64 to prevent overflow panics on 0xffff
That's your problem. The original C code relies on the operation overflowing. Increasing the size of the type doesn't fix it, but allowing the overflow to wrap does:
fn hamming_weight(val: u32) -> u32 {
let v1 = val - ((val >> 1) & 0x55555555);
let v2 = (v1 & 0x33333333) + ((v1 >> 2) & 0x33333333);
(((v2 + (v2 >> 4)) & 0xF0F0F0F).wrapping_mul(0x1010101)) >> 24
}

Related Links

How to check in Rust if architecture is 32 or 64 bit?
How can I succinctly combine many `Result`s of different types?
Why is the produced assembly not equivalent between returning by reference and copy when inlined?
include module from the same directory level [duplicate]
Is there a way to prevent emitted LLVM IR from removing unused functions?
Does Cargo support custom profiles?
Pass mutable reference to an element of a vector as parameter of function alongside with that vector
How to format a String object in Rust? [duplicate]
How do I make rustc-link-search relative to the project location?
Safe non-trivial data dependencies/custom references?
Skip struct field when serializing
Rust error E0495 using split_at_mut in a closure
What is the proper way to create a Span when inserting a new field with a Rust compiler plugin?
Using Any with traits in Rust [duplicate]
How do I create an iterator that invalidates the previous result each time `next` is called? [duplicate]
How can I better store a string to avoid many clones?

Categories

HOME
elasticsearch
memory
matrix
yahoo-weather-api
paypal-ipn
writefile
loopbackjs
biztalk
bing-search
google-webmaster-tools
phpmqtt
eddystone
mutation-testing
elastic-load-balancer
slide
chromecast
vimeo
pm2
angular4
django-rq
sonicwall
async-await
phonegap-build
nest-api
rest-assured
mixpanel
cloudsim
multiple-tables
spyder
gollum-wiki
sybase-ase
software-packaging
introspection
morris.js
background-color
ruby-daemons
code-climate
tsung
envoy
caesar-cipher
lxml
identify
game-center
suds
hdiv
word-cloud
latexml
docker-ucp
music21
django-static-precompiler
xcglogger
jgrapht
sharpdx
subforms
exc-bad-access
nslayoutconstraint
openerp-6
email-injection
annotatorjs
mifos
msg
raw-sockets
android-4.2-jelly-bean
bbc-micro
deferred-rendering
simian
android-async-http
swiffy
polymerfire
gwt-syncproxy
gravatar
servicestack-bsd
lovefield
ibm-was
arbre
dsa
libz
org-babel
ampersand
actionpack
deque
fasterxml
category-theory
zend-search-lucene
accountmanager
cpu-time
flipboard
spring-social-linkedin
profiles
quickgraph
office-app
xcode4.5
zend-pdf
first-class
memory-pool
net-use
mediacontroller
jmenu
git-log
bass
3-tier
browser-based
spring-modules
external-sorting
rtti
version-control-migration
twitter-feed

Resources

Database Users
RDBMS discuss
Database Dev&Adm
javascript
java
csharp
php
android
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App