Integer to Byte

D

Dante

I'm converting a C# program to VB.net, but i'm having
problems converting a integer to a byte in the same way as
the c# program does.

//C# program
int i = 137694;
byte b = (byte) i;
//b returns as value 222

'VB program
dim i as integer = 137694
dim b as byte = CByte(i)
'b returns Overflow Error

I understand that the CByte function only takes values
from 0 - 255, which is why the overflow error, but the c#
program casts from int to byte and gets a value of 222.
Anyone know how to get my VB.net app to do this?
 
R

Robert Jacobson

Well, it seems like the VB.Net way is technically correct, insofar as you
can't (correctly) cast a number greater than 255 to a byte. But if you're
just looking to extract the least-significant byte out of a longer number,
try using this formula in your code:

X Mod 256

With X being any integer.

E.g., 137694 Mod 256 = 222.
 
J

Jay B. Harlow [MVP - Outlook]

Dante,
In addition to Robert's comments (which I would recommend doing).

Remember that by default that overflow checking is on in VB.NET while it is
off by default in C#. Hence the exception in VB.NET, while truncation in C#.

Unfortunately the option to change overflow checking is at the project
level, not file, function, or statement level, which is why I would
recommend using the Mod operator as Robert suggests.

Hope this helps
Jay
 
D

Dante

Thanks, that works great, except for negative numbers do
not seem to work.
for example:

-10471344 mod 256 = -176

and in the c# program the value of -10471344 casted to a
byte is equal to 80
 
J

Jay B. Harlow [MVP - Outlook]

Dante,
Then you will need to 'normalize' it with a method other than the Mod
operator. (repeated subtraction or addition comes to mind).

Or keep that module in C#.

Or turn off the overflow checking.

Hope this helps
Jay
 
D

Dante

I figured it out, instead of using mod 256, if I AND the
integer with 255 it works

-10471344 AND 255 = 80

Thanks for your help!
 
R

Robert Jacobson

Good catch -- I didn't consider negative numbers as a possible input.

I noticed that 256 - 176 = 80. So, a quick fix is to use an if/then to test
whether the input is positive or negative. If it's negative, use the
following foruma:

256 + Abs (X Mod 256)

For example, if X is -10471344, it returns 80. X Mod 256 is a negative
number, so it's evaluated as 256 + (-176)

There might be a more elegant mathematical solution, but this should get the
job done.
 
R

Robert Jacobson

Just saw your solution (damn slow newsservers <g>.) This looks much better.
Good idea.
 
F

Fergus Cooney

Hi Jay,

ROFL - I didn't want to say anything but I was surprised. ;-)

Regards,
Fergus
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top