views:

81

answers:

4

Hey,

I have a need to mirror a byte's value around the centre of 128. So, example outputs of this function include:

In  0     Out  255
In  255   Out  0
In  128   Out  128
In  127   Out  129
In  30    Out  225
In  225   Out  30

I'm driving myself nuts with this, I'm sure I'll kick myself when I read the answers.

Cheers

+3  A: 

There is no obvious rule that matches your example output.

The first two and the last result could be explained by 255-n, which might be a normal interpretation of ‘mirroring’ a byte. But 128->128 would have to be 256-n, and 127->1 is seemingly inexplicable.

bobince
Used 255-n with a special condition for 128. Sorry about the weird 127->1 example.
Kazar
@Kazar: You don't want a special case for 128 - since there are an even number of possible bytes, there is no "center" value, so no value should map to itself when you reverse them like this. Eg: 255-127 is 128 (as it should be), not 129. If you really want to flip all the values about 128, you should use `256-n`, in which case `255->1`, and nothing goes to 0 (since 256 does not fit into one byte)
BlueRaja - Danny Pflughoeft
The ‘center’ (mean) value for the range of bytes 0–255 is 127.5. `255-n` mirrors around 127.5. If you wanted to mirror around exactly 128, you'd end up with values 1–256, which is fine but it doesn't fit in a byte. To make it fit in a byte you might clip to map both `1->255` and `0->255`, which is at least less of a discontinuity than special-casing `128->128` when `129->126`.
bobince
+1  A: 

The simple answer, which doesn't quite match your table, is 255 - v.

Marcelo Cantos
+1  A: 

How about this?

In  0     Out  255
In  255   Out  0
In  128   Out  127
In  127   Out  128
In  30    Out  225
In  225   Out  30

It will be 255-n

Behrooz
A: 

If you must stay within a byte, use (255-v) + (v==255)?0:1. Otherwise, use 256-v. That mirrors around 128. ~v (bitwise not) may be faster than 255-v if you want to mirror around 127.5.

Rex Kerr