jerry
jerry

Reputation: 71

convert type 'uint' to 'int' in C#

I am trying to assign an int to an hex number. const int a = 0xFFFFFFF0; I got an error: Cannot implicitly convert type 'uint'. An explicit conversion exsist (are you missing a cast?) Does someone know how to fix it? tnx

Upvotes: 7

Views: 12144

Answers (5)

dmihailescu
dmihailescu

Reputation: 1643

there is another way to convert without using the unchecked keyword:

uint ui = 0xFFFFFFFF;

int ii = System.BitConverter.ToInt32(BitConverter.GetBytes(ui),0);// this is -1

Upvotes: 0

Paolo Falabella
Paolo Falabella

Reputation: 25844

Int32.MaxValue is 0x7FFFFFFF . I guess c# is trying to convert the value you're trying to assing to a uint (which can accomodate it) before assigning it

Upvotes: 1

Axarydax
Axarydax

Reputation: 16603

store the 0xFFFFFFF0 variable into an uint, because it's too big to fit inside an int

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062840

    const int a = unchecked((int)0xFFFFFFF0);

or simpler:

    const int a = -16;

Upvotes: 16

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174319

use

const uint a = 0xFFFFFFF0

;-)

Background: 0xFFFFFFF0 is too big to fit into an int, which goes from − 2,147,483,648 to 2,147,483,647, where as uint goes from 0 to 4,294,967,295, which is just above 0xFFFFFFF0 (= 4,294,967,280).

Upvotes: 2

Related Questions