Request: code review

I need to implement this function over unbounded integers using bounded integers:

f(n) = n >= 0 ? n * 2 : n * -2 + 1

Please review my implementation. In particular, I need to make sure I didn't accidentally assume two's complement arithmetic.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
template <typename T>
std::make_unsigned<T>::type ints_to_uints(T z){
	typedef std::make_unsigned<T>::type u;
	
	if (z >= 0)
		return (u)z * 2;
	
	std::uint8_t lower = z % 256;
	z /= 256;
	u converted = -z;
	converted *= 256;
	converted += lower;
	return converted * 2 + 1;
}

EDIT: Oh, assume T is larger than char.
Last edited on
Line 8: In C++11 modulus returns negative value for negative operands. Then it cast to uint8_t using modulo 2n arithmetics guaranteed by standard.
Before C++11 it is all implementation defined.

Example for -257:

8: lower = -1 = 255;
9: z = -1;
10: converted = 1
11: converted = 256
12: converted = 511

You want to negate result of modulus first.
Last edited on
Great. Thanks!
Topic archived. No new replies allowed.