Convert Byte array to Int in xamarin pcl c# - c#

this is my problem: i need to convert bytes array to int in c#, on xamarin pcl.
But i have tryed this:
byte[] fromBoardSerial = new byte[3];
fromBoardSerial[0] = 0x04
fromBoardSerial[1] = 0x93
fromBoardSerial[2] = 0xe0
result = BitConverter.ToInt32(fromBoardSerial, 0);
Solution:
Array.Reverse(fromBoardSerial); //call before conversion
but the result is: -527236096...Instead..the correct result should be: 300000
how do conversion from array bytes in Int ?
Thanks

It looks like you have two problems here:
Number of bytes. You must have 4 bytes for conversion to Int32.
Byte order. It looks like you try to calculate your number "backwards".
Look at this code:
byte[] fromBoardSerial = new byte[4];
fromBoardSerial[0] = 0xe0;
fromBoardSerial[1] = 0x93;
fromBoardSerial[2] = 0x04;
fromBoardSerial[3] = 0x00;
var result = BitConverter.ToInt32(fromBoardSerial, 0); // result = 300000

Related

Kotlin equivalent of C# BitConverter.ToString

It's BitConverter.ToString(blabla) same with blabla.toString?
Example:
int values = 1500;
byte[] bytes = BitConverter.GetBytes(values);
byte[] bits = new byte[2];
bits.SetValue(bytes[0], 0);
bits.SetValue(bytes[1], 1);
string hex = BitConverter.ToString(bits);
string hexHub1 = hex.Substring(0, hex.IndexOf("-"));
string hexHub2 = hex.Substring(hex.IndexOf("-") +1,2);
And get "DC-05"
How can i implement anything like this in kotlin?
byteArray.toString() is used to convert ByteArray to String. On the other hand, contentToString() will result elements in the array.
val byteArray = "Hello".toByteArray(Charsets.UTF_8)
println(byteArray.contentToString()) // this will print numbers
println(byteArray.toString(Charsets.UTF_8))

How do I convert the decimal value in hex string and hex string and hex string to byte

I have bytes array of decimal values like [0, 4, 20, 141] and I want that to be converted as [0x00, 0x04, 0x14, 0x8D] which I need to use this array as bytes to add in a buffer
Current data:
byte[] packet = new byte[4];
packet[0] = 0;
packet[1] = 4;
packet[2] = 20;
packet[3] = 141;
and expected data to send to the serial port is as below:
byte[] mBuffer = new byte[4];
mBuffer[0] = 0x02;
mBuffer[1] = 0x04;
mBuffer[2] = 0x14;
mBuffer[3] = 0x8D;
Tried:
Convert.ToByte(string.Format("{0:X}", packet[0]));
But throwing an exception:
Input string was not in a correct format.
You're getting the exception because you're trying to substitute a variable in the string without the "$" prefix. Try this:
// Converts integer 141 to string "8D"
String parsed = String.Format($"{0:X}", packet[3]);
Then, you should be able to convert to a byte using this:
// Parses string "8D" as a hex number, resulting in byte 0x8D (which is 141 in decimal)
Byte asByte = Byte.Parse(parsed, NumberStyles.HexNumber);

C#: storing 16 bit data

I have written the following code in C# to get 16-bit twos compliment values over uart from 8 bit microcontroller. I am receiving data in bytes form. So I am combining the two bytes to form a 16-bit value. My issue is that my all values are becoming negative, but in reality some are negative some are not. Please tell me what is wrong of the following code that I am doing:
int t = 0;
int bytes = serialPort1.BytesToRead;
byte[] buffer = new byte[bytes];
serialPort1.Read(buffer, 0, bytes);
float [] buffer2 = new float[bytes];
for(int i=0;t< buffer.Length;i++)
{
buffer2[i]= ~(((buffer[t]<< 8) | buffer[t+1]) - 1);
t = t + 2;
}

convert byte array to uint numeric value

Let's say I have array of bytes
byte[] byteArr = new byte[] { 1, 2, 3, 4, 5 };
I want to convert this array to get regular numeric variable of uint, so result will be
uint result = 12345;
So far all the example I've seen were with bytes, byte I don't need bytes, but numeric value.
Thanks...
It sounds like you want something like:
uint result = 0;
foreach (var digit in array)
{
result = result * 10 + digit;
}
Or more fancily, using LINQ:
uint result = array.Aggregate((uint) 0, (curr, digit) => curr * 10 + digit);

Convert byte array to int

I am trying to do some conversion in C#, and I am not sure how to do this:
private int byteArray2Int(byte[] bytes)
{
// bytes = new byte[] {0x01, 0x03, 0x04};
// how to convert this byte array to an int?
return BitConverter.ToInt32(bytes, 0); // is this correct?
// because if I have a bytes = new byte [] {0x32} => I got an exception
}
private string byteArray2String(byte[] bytes)
{
return System.Text.ASCIIEncoding.ASCII.GetString(bytes);
// but then I got a problem that if a byte is 0x00, it show 0x20
}
Could anyone give me some ideas?
BitConverter is the correct approach.
Your problem is because you only provided 8 bits when you promised 32. Try instead a valid 32-bit number in the array, such as new byte[] { 0x32, 0, 0, 0 }.
If you want an arbitrary length array converted, you can implement this yourself:
ulong ConvertLittleEndian(byte[] array)
{
int pos = 0;
ulong result = 0;
foreach (byte by in array) {
result |= ((ulong)by) << pos;
pos += 8;
}
return result;
}
It's not clear what the second part of your question (involving strings) is supposed to produce, but I guess you want hex digits? BitConverter can help with that too, as described in an earlier question.
byte[] bytes = { 0, 0, 0, 25 };
// If the system architecture is little-endian (that is, little end first),
// reverse the byte array.
if (BitConverter.IsLittleEndian)
Array.Reverse(bytes);
int i = BitConverter.ToInt32(bytes, 0);
Console.WriteLine("int: {0}", i);
this is correct, but you're
missing, that Convert.ToInt32
'wants' 32 bits (32/8 = 4 bytes)
of information to make a conversion,
so you cannot convert just One byte:
`new byte [] {0x32}
absolutely the the same trouble
you have. and do not forget about
the encoding you use: from encoding to encoding you have 'different byte count per symbol'
A fast and simple way of doing this is just to copy the bytes to an integer using Buffer.BlockCopy:
UInt32[] pos = new UInt32[1];
byte[] stack = ...
Buffer.BlockCopy(stack, 0, pos, 0, 4);
This has the added benefit of being able to parse numerous integers into an array just by manipulating offsets..

Categories