Conversion from Long to Byte

vishalkbhatt

Member
Joined
Oct 7, 2010
Messages
12
Programming Experience
Beginner
Hi friends, I m new to this forum and also to VB.net programming. In an application Modbus protocol is used and I have generate LRC checksum for that. But I am stuck at conversion of a Long type data to Byte type. The long type data is for example : 4294967197. I tried all the following functions:
1.b = Byte.Parse(4294967197)
2.b = CByte(4294967197)
3.b = Convert.ToByte(4294967197)
But all give me Overflow errors. the same conversion happens in C# by the statement : byte b = (byte) 4294967197; The answer for this is 9D.
So anyone who knows a function to achieve this conversion or any other way to to this then pls reply, Thanks in advance...
 
Long data type is 64 bits (Int64), which is 8 bytes, and you can't fit 8 bytes into 1 byte. If you get the byte values for that Long using BitConverter.GetBytes and take the first byte value you get 157, which converted to a hex string is value "9D".

Note if you convert that Byte back to Long you still get the value 157, the other 7 bytes is lost. It is said that converting a value of a data type to another that has a greater range is a widening conversion, and the opposite is a narrowing conversion. But when value is not representable in a narrowing conversion you get as experienced an overflow exception, converting that value to a narrower data type is simply not possible. So only taking part of the original value, ie here first of eight bytes, is questionable.
 
the same conversion happens in C# by the statement : byte b = (byte) 4294967197; The answer for this is 9D.

Actually what you're doing in C# is ignoring the higher bytes and only getting the value of the LSB (least significative byte). That is very different from a conversion.
To do that in vb.net you could simply convert it to Hex representation, then ToString, cut it out the (substring) the right 2 chars and then convert back to fit byte, but I'll repeat in bold letters: This is very very different from conversion.
 
simply convert it to Hex representation, then ToString, cut it out the (substring) the right 2 chars and then convert back to fit byte,
BitConverter is simpler :) But, you're right this is rather part extraction than conversion.
 
Back
Top