Bytes to integer conversion - c#

I need to convert the byte data to integer:
byte[] mode = new byte[3] {50, 53, 53};
I tried to convert using BitConverter.ToInt32(mode, 0) but got an exception:
Destination array is not long enough to copy all the items in the collection. Check array index and length.
Update: The expected result after conversion is 255.

It's not clear what you're trying to achieve, but BitConverter.ToInt32 requires 4 bytes of data to work with and you're passing it an array of 3 bytes. Add one more byte and it will work, meaning it will not throw an exception and will do the conversion, but I'm not sure if it will give you want you want.
Example:
byte[] mode = new byte[4] {50, 53, 53, 00};
var result = BitConverter.ToInt32(mode, 0); //Result will be 3487026
EDIT Apparently this array represents text, not an integer. To convert it, you need to know the encoding used. If it is guaranteed to have only numbers, then you can use ASCII:
byte[] mode = new byte[3]{50, 53, 53};
string result = System.Text.Encoding.ASCII.GetString(mode); //Result will be 255
Now, if you want to convert it to an integer, then it is simple. Use any conversion method like int.Parse() or Convert.ToInt32().

Related

c# convert 2 bytes into int value

First, I had read many posts and tried BitConverter methods for the conversion, but I haven't got the desired result.
From a 2 byte array of:
byte[] dateArray = new byte[] { 0x07 , 0xE4 };
Y need to get an integer with value 2020. So, the decimal of 0x7E4.
Following method does not returning the desired value,
int i1 = BitConverter.ToInt16(dateArray, 0);
The endianess tells you how numbers are stored on your computer. There are two possibilities: Little endian and big endian.
Big endian means the biggest byte is stored first, i.e. 2020 would become 0x07, 0xE4.
Little endian means the lowest byte is stored first, i.e. 2020 would become 0xE4, 0x07.
Most computers are little endian, hence the other way round a human would expect. With BitConverter.IsLittleEndian, you can check which type of endianess your computer has. Your code would become:
byte[] dateArray = new byte[] { 0x07 , 0xE4 };
if(BitConverter.IsLittleEndian)
{
Array.Reverse(dataArray);
}
int i1 = BitConverter.ToInt16(dateArray, 0);
dateArray[0] << 8 | dateArray[1]

Unhandled exception converting to byte

As the title implies, I'm getting "An unhandled exception of type 'System.FormatException'" style message. Need some help figuring out why. I'm reading in a file that has a hex value I need to parse. The value I'm reading it could look something like this "0x12345678" (4 bytes in length).
The first byte (note this is little endian) is 'BE' and I can get that no problem. My issue is then trying to take the next three bytes and convert that into a human readable int. (Long story, but the program that generates the output I'm parsing takes a human readable decimal number and converts it to this LE nonsense.)
string parmVal = lineF.Substring((pos + length)); // this is "0x12345678"
string hexID = parmVal.Substring(2, 2); // stores '12'
byte[] testID = new byte[4];
testID[0] = Convert.ToByte(parmVal.Substring(4, 2)); <----error here
testID[1] = Convert.ToByte(parmVal.Substring(6, 2));
testID[2] = Convert.ToByte(parmVal.Substring(8, 2));
testID[3] = Convert.ToByte(0);
decimalID = int.Parse(hexID, System.Globalization.NumberStyles.HexNumber); // stores 18 (0x12)
testIDNumber = BitConverter.ToInt32(testID,0); // stores 345678
Interestingly, in the code I later output these values to a CSV file, and the values I print out look correct, even though its throwing the exception. I tried reading in the last 3 bytes the same way as the first by, but then when I do the int.Parse() on it, it gets its endian-ness backwards. Where I'd want it to convert 0x"785634", its converting 0x"345678".
Try to specify base in Convert.ToByte call.
In your case it has to be:
testID[0] = Convert.ToByte(parmVal.Substring(4, 2), 16);

Read and write more than 8 bit symbols

I am trying to write an Encoded file.The file has 9 to 12 bit symbols. While writing a file I guess that it is not written correctly the 9 bit symbols because I am unable to decode that file. Although when file has only 8 bit symbols in it. Everything works fine. This is the way I am writing a file
File.AppendAllText(outputFileName, WriteBackContent, ASCIIEncoding.Default);
Same goes for reading with ReadAllText function call.
What is the way to go here?
I am using ZXing library to encode my file using RS encoder.
ReedSolomonEncoder enc = new ReedSolomonEncoder(GenericGF.AZTEC_DATA_12);//if i use AZTEC_DATA_8 it works fine beacuse symbol size is 8 bit
int[] bytesAsInts = Array.ConvertAll(toBytes.ToArray(), c => (int)c);
enc.encode(bytesAsInts, parity);
byte[] bytes = bytesAsInts.Select(x => (byte)x).ToArray();
string contentWithParity = (ASCIIEncoding.Default.GetString(bytes.ToArray()));
WriteBackContent += contentWithParity;
File.AppendAllText(outputFileName, WriteBackContent, ASCIIEncoding.Default);
Like in the code I am initializing my Encoder with AZTEC_DATA_12 which means 12 bit symbol. Because RS Encoder requires int array so I am converting it to int array. And writing to file like here.But it works well with AZTEC_DATA_8 beacue of 8 bit symbol but not with AZTEC_DATA_12.
Main problem is here:
byte[] bytes = bytesAsInts.Select(x => (byte)x).ToArray();
You are basically throwing away part of the result when converting the single integers to single bytes.
If you look at the array after the call to encode(), you can see that some of the array elements have a value higher than 255, so they cannot be represented as bytes. However, in your code quoted above, you cast every single element in the integer array to byte, changing the element when it has a value greater than 255.
So to store the result of encode(), you have to convert the integer array to a byte array in a way that the values are not lost or modified.
In order to make this kind of conversion between byte arrays and integer arrays, you can use the function Buffer.BlockCopy(). An example on how to use this function is in this answer.
Use the samples from the answer and the one from the comment to the answer for both conversions: Turning a byte array to an integer array to pass to the encode() function and to turn the integer array returned from the encode() function back into a byte array.
Here are the sample codes from the linked answer:
// Convert byte array to integer array
byte[] result = new byte[intArray.Length * sizeof(int)];
Buffer.BlockCopy(intArray, 0, result, 0, result.Length);
// Convert integer array to byte array (with bugs fixed)
int bytesCount = byteArray.Length;
int intsCount = bytesCount / sizeof(int);
if (bytesCount % sizeof(int) != 0) intsCount++;
int[] result = new int[intsCount];
Buffer.BlockCopy(byteArray, 0, result, 0, byteArray.Length);
Now about storing the data into files: Do not turn the data into a string directly via Encoding.GetString(). Not all bit sequences are valid representations of characters in any given character set. So, converting a random sequence of random bytes into a string will sometimes fail.
Instead, either store/read the byte array directly into a file via File.WriteAllBytes() / File.ReadAllBytes() or use Convert.ToBase64() and Convert.FromBase64() to work with a base64 encoded string representation of the byte array.
Combined here is some sample code:
ReedSolomonEncoder enc = new ReedSolomonEncoder(GenericGF.AZTEC_DATA_12);//if i use AZTEC_DATA_8 it works fine beacuse symbol size is 8 bit
int[] bytesAsInts = Array.ConvertAll(toBytes.ToArray(), c => (int)c);
enc.encode(bytesAsInts, parity);
// Turn int array to byte array without loosing value
byte[] bytes = new byte[bytesAsInts.Length * sizeof(int)];
Buffer.BlockCopy(bytesAsInts, 0, bytes, 0, bytes.Length);
// Write to file
File.WriteAllBytes(outputFileName, bytes);
// Read from file
bytes = File.ReadAllBytes(outputFileName);
// Turn byte array to int array
int bytesCount = bytes.Length * 40;
int intsCount = bytesCount / sizeof(int);
if (bytesCount % sizeof(int) != 0) intsCount++;
int[] dataAsInts = new int[intsCount];
Buffer.BlockCopy(bytes, 0, dataAsInts, 0, bytes.Length);
// Decoding
ReedSolomonDecoder dec = new ReedSolomonDecoder(GenericGF.AZTEC_DATA_12);
dec.decode(dataAsInts, parity);

BitConverter.ToInt32 to convert 2 bytes

I am using BitConverter.ToInt32 to convert a Byte array into int.
I have only two bytes [0][26], but the function needs 4 bytes, so I have to add two 0 bytes to the front of the existing bytes.
What is the quickest method.
Thank you.
You should probably do (int)BitConverter.ToInt16(..) instead. ToInt16 is made to read two bytes into a short. Then you simply convert that to an int with the cast.
You should call `BitConverter.ToInt16, which only reads two bytes.
short is implicitly convertible to int.
Array.Copy. Here is some code:
byte[] arr = new byte[] { 0x12, 0x34 };
byte[] done = new byte[4];
Array.Copy(arr, 0, done, 2, 2); // http://msdn.microsoft.com/en-us/library/z50k9bft.aspx
int myInt = BitConverter.ToInt32(done); // 0x00000026
However, a call to `BitConverter.ToInt16(byte[]) seems like a better idea, then just save it to an int:
int myInt = BitConverter.ToInt16(...);
Keep in mind endianess however. On little endian machines, { 0x00 0x02 } is actually 512, not 2 (0x0002 is still 2, regardless of endianness).

Bits into char array

I need to transfrom bits into char array or string, help to find best way to store bits and what shoud I do if for example I have 18 bits I will make 2 char and 2 bits?
The best way to store bits in C# is in the BitArray class, if you just need them as bits. If you need the integer value of the 18 bits, then you have to convert them to int or double or whatever.
First step would be to convert your bit array into bytes and once you have an array of bytes you will need to choose a proper encoding and convert to a string which is an array of chars:
BitArray bitArray = new BitArray(new[] { true, false, true, false, });
byte[] bytes = new byte[bitArray.Length];
bitArray.CopyTo(bytes, 0);
char[] result = Encoding.UTF8.GetString(bytes).ToCharArray();
Obviously you need to know the encoding of those bits in order to be able to convert to characters. If you don't know the encoding you should reconsider what you are trying to do.

Categories

Resources