Get start position of byte chunk from a byte array [duplicate] - c#

This question already has answers here:
byte[] array pattern search
(29 answers)
Closed 9 years ago.
Supposing I have a byte array of size 4096, what's an efficient way to get the start position of a chunk of say... 5 bytes that matches a pattern?
For e.g., I would like to get the start position of the 1st possible match of the byte array
var match = new byte[] { 0x03, 0x04, 0x05, 0x06, 0x07 };
So if the above chunk is found within my byte array, it will return me the position of the 1st byte (0x03)

You can use Linq:
public static int IndexOfArray<T>(T[] source, T[] search)
{
var result = Enumerable.Range(0, source.Length - search.Length)
.Select(i => new
{
Index = i,
Found = source.Skip(i)
.Take(search.Length)
.SequenceEqual(search)
})
.FirstOrDefault(e => e.Found);
return result == null ? -1 : result.Index;
}

Related

C# : how to convert char array into float [duplicate]

This question already has answers here:
problem converting 4-bytes array to float in C#
(3 answers)
Closed 9 months ago.
I have a byte array of four bytes which contains the byts of a FLOAT values.
For example
array[0]=0x1F
array[1]=0x05
array[2]=0x01
array[3]=0x42
this should be 0x4201051f, which means 32.255 value.
Do you have any suggestion on how to group the array and save the value in a float data?
Thank you
As suggested by shingo, the linked question provides the answer:
var input = new byte[] { 0x1F, 0x05, 0x01, 0x42 };
Console.WriteLine(BitConverter.ToSingle(input, 0)); // Outputs 32.255

How to convert byte[512] to string 1024 length [duplicate]

This question already has answers here:
How do you convert a byte array to a hexadecimal string, and vice versa?
(53 answers)
Closed 5 years ago.
This bit of code produces an array of size 512, it converts a string that was originally 1024 characters in length and has hex data.
byte[] content = Enumerable.Range(0, data.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(data.Substring(x, 2), 16))
.ToArray();
I like to know how to reverse this so taking a byte[512] I want to produce the 1024 length string containing the hex data.
Try with
var result = string.Join("",
inputString.Select(c => String.Format("{0:X2}", Convert.ToInt32(c))));

Convert to base 2 then split in an array [duplicate]

This question already has answers here:
Convert int to a bit array in .NET
(10 answers)
Closed 7 years ago.
I want to convert my base 10 number to base 2 and then store parts in an array.
Here are two examples:
my value is 5 so it will be converted to 101 then I have an array like this: {1,0,1}
or my value is 26 so it will be converted to 11010 then I will have an array like this: {0,1,0,1,1}
Thank you in advance for your time and consideration.
To convert the int 'x'
int x = 3;
One way, by manipulation on the int :
string s = Convert.ToString(x, 2); //Convert to binary in a string
int[] bits= s.PadLeft(8, '0') // Add 0's from left
.Select(c => int.Parse(c.ToString())) // convert each char to int
.ToArray(); // Convert IEnumerable from select to Array
Alternatively, by using the BitArray class-
BitArray b = new BitArray(new byte[] { x });
int[] bits = b.Cast<bool>().Select(bit => bit ? 1 : 0).ToArray();
Source: https://stackoverflow.com/a/6758288/1560697

Converting int value into 3 byte array (and vice versa)

I am working on a C# WinForms application that reads/writes data to/from a hardware device. My application has a multiselect listbox which contains the numbers 1 - 100000 and the user may select up to 10 numbers. When they're done selecting each number, the user clicks a button and my event handler code needs to build a fixed-size (30 bytes) byte array using 3 bytes to represent each selected number and pad the array if less than 10 numbers were selected.
As an example, suppose my user chooses the following values:
17
99152
3064
52588
65536
I'm currently using this code to convert each number into a byte array:
byte[] bytes = BitConverter.GetBytes(selectedNumber);
Array.Reverse(bytes) // because BitConverter.IsLittleEndian() = true
Debug.WriteLine(BitConverter.ToString(bytes));
For the numbers I listed above, this produces the following:
00-00-00-11
00-01-83-50
00-00-0B-F8
00-00-CD-6C
00-01-00-00
BitConverter is giving me back a 4 byte array where I only have space to use 3 bytes to store each number in the final byte array. I can drop the most significant byte of each individual byte array and then build my final array like this:
00-00-11-01-83-50-00-0B-F8-00-CD-6C-01-00-00-[padding here]
Writing that to the device should work. But reading the array (or a similar array) back from the device causes a bit of a problem for me. When I have a 3 byte array and try to convert that into an int using this code...
int i = BitConverter.ToInt32(bytes, 0);
...I get "Destination array is not long enough to copy all the items in the collection." I suppose I could insert a most significant byte of 0x00 at the beginning of every three bytes and then convert that but is there a better way to do this?
I would imagine bit shifting and the | operator should be the most efficient way of doing this.
int i = (bytes[2] << 0) | (bytes[1] << 8) | (bytes[0] << 16);
Also, as a heads up, you're dropping the most significant byte, not the least significant byte ;p
byte[] bytes = new byte[] { 0x00, 0x00, 0x11, 0x01, 0x83, 0x50, 0x00, 0x0B, 0xF8 };
var ints = bytes.Select((b, i) => new { b, i })
.GroupBy(x => x.i / 3)
.Select(g => BitConverter.ToInt32(
new byte[] { 0 }.Concat(g.Select(x => x.b))
.Reverse()
.ToArray(),
0))
.ToArray();
or classically
var ints = new List<int>();
for (int i = 0; i < bytes.Length; i+=3)
{
int intI=0;
for (int j = i; j < i + 3; j++)
{
intI = intI * 256 + bytes[j]; //or (intI << 8) + bytes[j];
}
ints.Add(intI);
}
ints will be 17, 99152 and 3064

Operations on BitArray [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How i can convert BitArray to single int?
How can I read an integer to a BitArray(6) (assuming it can be contained) and how to convert a BitArray(6) to unsigned/signed integer.
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);
// Output: int: 25
BitArray FromInt32(Int32 a)
{
byte[] bytes = BitConverter.GetBytes(a);
return new BitArray(bytes);
}
For reverse operaton see this question as mentioned before.

Categories