c# - Mathematical operations on packed numerical values -
given following code packing 4 byte
values uint
.
private static void pack(byte x, byte y, byte z, byte w) { this.packedvalue = (uint)x | ((uint)y << 8) | ((uint)z << 16) | ((uint)w << 24); }
is possible apply mathematical operators *, +, / , -
on value in manner can unpacked correct byte
equivalent?
edit.
to clarify, if attempt multiply value packed value
uint result = this.packedvalue * other.packedvalue
then unpack using following...
public byte[] tobytes() { return new[] { (byte)(this.packedvalue & 0xff), (byte)((this.packedvalue >> 8) & 0xff), (byte)((this.packedvalue >> 16) & 0xff), (byte)((this.packedvalue >> 24) & 0xff) }; }
i wrong results.
here's full code sample showing expected , actual result.
void main() { uint x = packuint(128, 128, 128, 128); uint y = (uint)(x * 1.5f); byte[] b1 = tobytes(x); x.dump(); // 2155905152 b1.dump(); // 128, 255, 128, 255 right! byte[] b2 = tobytes(y); b2.dump(); // 0, 192, 192, 192 wrong! should 192, 192, 192, 192 } // define other methods , classes here private static uint packuint(byte x, byte y, byte z, byte w) { return ((uint)x) | ((uint)y << 8) | ((uint)z << 16) | ((uint)w << 24); } public static byte[] tobytes(uint packed) { return new[] { (byte)(packed & 0xff), (byte)((packed >> 8) & 0xff), (byte)((packed >> 16) & 0xff), (byte)((packed >> 24) & 0xff) }; }
the reason doesn't work 1.5f
because floats not precise enough. try 1.5d
(for double
) , example work. approach limited "nice" cases, i.e. result in each byte guaranteed whole number. special case when multiply integer, work long none of 4 results overflow.
it possible addition , subtraction provided none of individual bytes overflow. overflow mess nearby bytes. particularly problematic if wish use 2's complement negative bytes (-128 .. 127) because adding 3 -2 "overflow" , mess next byte.
Comments
Post a Comment