Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Friday, September 28, 2007 4:04 AM
I have a binary file, which stores each integer value in just 1 byte, is it possible to convert 1 byte directly into an integer value?
I know, there is function like: BitConverter.ToInt16(buf, 0), but this function require the buf length is 2, if my buf length is 1, Can I convert it to integer values without converting the buf to length 2 buf?
Thanks,
Rex
All replies (4)
Friday, September 28, 2007 4:42 AM ✅Answered
Casting works fine when going from smaller data types into compatible larger ones.
Just read in the values as a byte and cast to an integer. int value = (int)someByteValue;
Friday, September 28, 2007 7:10 AM ✅Answered
You don't have BitConverter.ToByte to get single byte because you don't need to. All you have to do is to get the byte from bytes buffer on specific position.
instead of this:
int value = BitConverter.ToInt16(byteBuffer, placeToStart); //problem with this is that you don't want to read two bytes
do this:
int value = byteBuffer[placeToStart];
Saturday, September 29, 2007 3:01 PM ✅Answered
Hi, Rex
You have to for the BitConverter.ToInt32 must be able to read 4 byte to complete the conversion. Or you can make a special converter yourself which can convert 3 bytes to an integer.
Friday, September 28, 2007 8:34 PM
Thanks Steve and Boban, that works for me. Now I have one more further question. If all integer are stored in 3 bytes, after I read them, do I have to copy the 3-byte buf to 4-byte buffer so that I can use BitConverter.ToInt32(buf, 0) function?
Thanks,
Rex