Question

I have a fast bit-level routine that calculates a value, and returns a UInt32. I need to store this value in SQL Server in a 32 bit int field. I don't want to increase the size of the field, and just want to store the "bytes" from this function the int field.

Hundreds of these records are requested at a time, so I need the fastest way to convert a UInt32 to int in a loop. If the left-most bit is set in the UInt32, it should set the sign bit of the int (or do anything "repeatable", really, but the sign bit would probably be easiest).

In other words, I just want the 4 bytes of a UInt32 to become the 4 bytes of an 32 bit int. I could use the BitConverter class, but I'm not sure that's the fastest way. Would it be faster to do this with an unchecked area like this:

UInt32 fld = 4292515959;
unchecked {
    return (int)fld;
    // -2451337
}

I see the reverse question has been asked here, and was just wondering if the answer would be the same going the other way:

Fastest way to cast int to UInt32 bitwise?

Was it helpful?

Solution

I'd say the unchecked version (like unchecked((int)x)) is the fastest way, since there's no method call. I don't believe there's a faster way.

By the way, UInt32 is just another name for uint... going one way is the same as going another way in terms of performance, so this is really the same as the link you posted.


Edit: I remember observing first-hand an instance of a benchmark where checked was faster than unchecked (and no, it wasn't a debug build, it was a release build with optimizations). I don't know why that happened, but in any case, don't think that you'll gain anything measurable by turning of overflow checking.

OTHER TIPS

unchecked((int)x) is required only casting consts and checked and unchecked produces the same results (if the code can compile).

For example this code

uint data = 4292515959;
int uncheckedData;
int checkedData;
unchecked {
    uncheckedData = (int)data;
}
checkedData = (int)data;

Console.WriteLine(data);
Console.WriteLine(uncheckedData);
Console.WriteLine(checkedData);

produces this output

4292515959
-2451337
-2451337

To be more concise, this code can be compiled (same result as unchecked((int)data))

uint data = 4292515959;
checkedData = (int)data;

This code (note the const) can't be compiled (requires unchecked)

const uint data = 4292515959;
checkedData = (int)data;

This code can't be compiled as well (requires unchecked)

checkedData = (int)4292515959;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top