Is there an easy way to convert from 32bit integer to 16bit integer?

I have a 32 bit int and I want to address only the lower half of this variable. I know I can convert to bit array and to int16, but is there any more straight forward way to do that?

Upvotes: 5

Views: 8387

Answers (6)

Will Dean
Will Dean

Reputation: 39520

It you want only the lower half, you can just cast it: (Int16)my32BitInt

In general, if you're extending/truncating bit patterns like this, then you do need to be careful about signed types - unsigned types may cause fewer surprises.

As mentioned in the comments - if you've enclosed your code in a 'checked' context, or changed your compiler options so that the default is 'checked', then you can't truncate a number like this without an exception being thrown if there are any non-zero bits being discarded - in that situation you'd need to do:

(UInt16)(my32BitInt & 0xffff)

(The option of using signed types is gone in this case, because you'd have to use & 0x7fff which then preserves only 15 bits)

Upvotes: 8

Luaan
Luaan

Reputation: 63772

Well, first, make sure you actually want to have the value signed. uint and ushort are there for a reason. Then:

ushort ret = (ushort)(val & ((1 << 16) - 1));

Upvotes: 0

drew_w
drew_w

Reputation: 10430

If you need a 16 bit value and you happen to know something specific like that the number will never be less than zero, you could use a UINT16 value. That conversion looks like:

 int x = 0;
 UInt16 value = (UInt16)x;

This has the full (positive) range of an integer.

Upvotes: 0

vcsjones
vcsjones

Reputation: 141678

If you force an unchecked operation, a cast should work:

int r = 0xF000001;
short trimmed = unchecked((short) r);

This will truncate the value of r to fit in a short.

If the value of r should always fit in a short, you can just do a normal cast and let an exception be thrown.

Upvotes: 1

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98840

You can use implicit conversation to Int16 like;

(Int16)2;

but be careful when you do that. Because Int16 can't hold all possible Int32 values.

For example this won't work;

(Int16)2147483683;

because Int16 can hold 32787 as maximum value. You can use unchecked (C# Reference) keyword such this cases.

Upvotes: 1

BRAHIM Kamel
BRAHIM Kamel

Reputation: 13774

just use this function

Convert.ToInt16()

or just

  (Int16)valueasint

Upvotes: 3

Related Questions