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

Can I determine the zero value of generic types?
How to slice a large Vec<i32> as &[u8]?
How to parse i64 from a string? [duplicate]
Why is variable scope dependent on the definition order?
Warning on “unstable” directive
How can I pass a socket as an argument to a function being called within a thread?
error: cannot move out of borrowed content on &mut self
Why does a reference not live long enough in case of “as_slice”?
Getting the error “error: the trait `core::marker::Sized` is not implemented” when trying to return the value from a vector
Traits with associated type in templates
Error handling best-practices
How to call count on an iterator and still use the iterator's items?
Caught between a lifetime and an FFI place
How to swap elements of array?
error: cannot assign to immutable indexed content `i[..]`
How to make a vector of received size?

Categories

HOME
jboss
android-studio
eclipse-plugin
livecode
adobe
mathematical-optimization
greasemonkey
ontology
selection
sharepoint-online
stack-overflow
siesta
circleci
clish
squirrel-sql
jodatime
android-contacts
rpmbuild
checkout
cpu-usage
deepfreeze
adobe-illustrator
dashdb
uislider
eclipse-emf
cell
prompt
uri
gravity-forms-plugin
bobo-browse.net
javax.persistence
es6-modules
vcenter
rust-cargo
spring-rabbitmq
dreamfactory
netstat
cheat-engine
daz3d
solr-query-syntax
embedded-v8
palindrome
clrs
rcharts
openerp-6
mifos
ftp-client
highlighting
django-validation
ioexception
webgrind
cortana
boost-proto
textpattern
msgpack
place
ambiguity
srv-record
netdatacontractserializer
uitest
com0com
kotlin-android-extensions
uno
operands
dc
wicket-1.5
windows-rt
squeezebox
distributed-r
proxy-server
sql-view
virtual-channel
chartfx
asp.net-mvc-3-areas
jquery-cycle
2d-vector
office-app
telerik-ajax
prototypal-inheritance
uploading
litespeed
botnet
pyjamas
mygeneration
index.dat
activex-exe

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App