vendredi 3 juillet 2015

Mapping signed integer ranges to unsigned

I'm facing a problem where signed integers should be converted to unsigneds, preserving their range.

Given the following definition:

#include <limits>

#define MAX(X) std::numeric_limits<X>::max();

What is the fastest and correct way to map the signed range [-MAX(T), +MAX(T)] to the unsigned range [0, MAX(U)]?

where:

T is a signed integer type

U is an unsigned integer type

sizeof(T) == sizeof(U)

I tried various bit twiddling and numeric methods to come up with a solution, without success.

Aucun commentaire:

Enregistrer un commentaire