pfinferno
pfinferno

Reputation: 1953

Can't convert int to byte

I'm in the process of converting a Delphi app to C#, and I came across this:

alength:=1; //alength is a byte
aa:=astring //astring is a string parameter passed into the function containing all this

alength:=strtoint(copy(aa,2,length(aa)-1));

So copy creates a string from part of an existing string, with the first character of the string starting at index 1, not 0 like other languages. It uses this format:

function copy ( Source : string; StartChar, Count : Integer ) : string;

And then strtoint which converts a string to an int.

For my c# conversion of that bit of code, I have:

alength = Convert.ToInt32(aa.Substring(1 ,aa.Length - 1));

which gives me the error Error 131 Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)

Since alength is already type byte, I didn't think I had to cast it?

Upvotes: 3

Views: 16001

Answers (4)

mikl _
mikl _

Reputation: 1

can use 0xFF because there is no difference & 0x000000FF == 0xFF

Upvotes: -2

Daniel Mizerski
Daniel Mizerski

Reputation: 1131

The pure cast can also work.

The byte is approx max 255 combinations I belive, so:

byte i = int_variable & 0x000000FF;

Will be fully controled cast.

Upvotes: 0

Alexander Derck
Alexander Derck

Reputation: 14498

You're using Convert.ToInt32() when you're assigning a byte. Use Convert.ToByte() instead.

Even better would be to use TryParse instead to avoid exceptions when the string isn't valid:

byte alength;
bool success = Byte.TryParse(aa.SubString(1,aa.Length - 1), out alength);

If the parsing succeedded success will be true, otherwise false. You can define the flow of your program depending on whether the conversion succeeds or not:

byte alength;
if(Byte.TryParse(aa.SubString(1,aa.Length - 1), out alength))
{
   //Great success! continue program
}
else
{
   //Oops something went wrong! 
}

Upvotes: 3

Ian
Ian

Reputation: 30823

Simply change:

alength = Convert.ToInt32(aa.Substring(1 ,aa.Length - 1));

into

alength = Convert.ToByte(aa.Substring(1 ,aa.Length - 1));

But more important question here would be: what is the range of value for aa string in the original use? Is it 0-255? If it is, then you can simply use ToByte, but if it is not, then you should think of using other data type.

Something like this:

int alength = Convert.ToInt32(aa.Substring(1 ,aa.Length - 1)); //define as int

Upvotes: 1

Related Questions