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.
Related
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
I have two byte arrays, they have variable length but always add up to 8 bytes. These need to be combined into a long. I can do this with creating a byte array and copying the required data. But I was thinking that this should also be possible through bit-shifting. I've been trying this (simplified with just one length):
var bytes1 = new byte[] { 1, 2, 3, 4, 5, 6, 7 };
var bytes2 = new byte[] { 8 };
unsafe
{
fixed (byte* b1 = bytes1)
{
fixed (byte* b2 = bytes2)
{
ulong* bl1 = (ulong*)b1;
ulong v = (*bl1<< 8) | (*b2);
var bytes = bytes1.Concat(bytes2).ToArray();
// These two are different:
Console.WriteLine(v);
Console.WriteLine(BitConverter.ToUInt64(bytes, 0));
}
}
}
I'm aware that Concat works, but I'd like to this to work too.
First of all, (ulong*)b1 is an out of bounds read because the array has length 7 and sizeof(ulong) == 8. The next read is also broken in that way. Alignment is also a problem. I don't see a way to rescue that approach. You could read 4 bytes, then 2 bytes, then 1 byte if you really are looking for performance.
I'd loop over the arrays and shift in each byte:
ulong result = 0;
void MergeArray(byte[] bytes) {
foreach (var b in bytes) {
result = result << 8 | (ulong)b;
}
}
MergeArray(bytes1);
MergeArray(bytes2);
Using a local function for code sharing.
You can improve performance by taking 4 bytes as the first chunk if the array length supports a read of that size. Then, fetch 2, then fetch 1. That way there is not even a loop and the number of operations is minimized.
Whether this is good or not depends on your need for performance which must be traded off with code legibility.
This question already has answers here:
How to convert UTF-8 byte[] to string
(16 answers)
Closed 7 years ago.
I want to read a file using File.Readallbytes(myfile) and to convert it to String like
string s=ByteArraytoString(File.Readallbytes(myfile));
but it doesn't really works for every file i choose, instead when the file is unicode it works file otherwise it doesn't ,so if any one can help me in this
public static string ByteArrayToString(byte[] bytes)
{
char[] chars = new char[(bytes.Length / sizeof(char))];
Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}
public static byte[] StringToByteArray(string s)
{
byte[] bytes = new byte[s.Length * sizeof(char)];
Buffer.BlockCopy(s.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
so the exception is: in ByteArrayToString method
System.ArgumentException: Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.
at System.Buffer.BlockCopy(Array src, Int32 srcOffset, Array dst, Int32 dstOffset, Int32 count)
i know this soloution posted like 1000 time but no one fix this problem in this code
First, you need to know what the encoding is for your file. Then, you can just use the System.Text.Encoding class to conveniently convert the byte array to a string.
For instance, if your file is in UTF-8, you can simply do:
string s = System.Text.Encoding.UTF8.GetString(bytes);
If your encoding is different, just pick a different property from the Encoding class, but the pattern is the same.
EDIT: Short explanation as to why OP's code did not work
The code in your original post tries to interpret the byte array as if it was already in the same encoding as the char type, which is UTF-16. So, unless your file happens to use UTF-16 encoding, it simply won't work. Using the Encoding class is the way to go.
why don't you try with default encoding
see below snippet
var strString = System.Text.Encoding.Default.GetString(File.Readallbytes(myfile));
so i solve the problem with this code
it gives me error in ByteArrayToString because the bytes.length is odd
so what i do is to check if the bytes.length is even it do the code normally but when it's odd it add one byte as {0} to the end of bytes to it will be even
here is my code:
if (bytes.Length % 2 != 0) {
byte[] newArray = new byte[bytes.Length + 1];
bytes.CopyTo(newArray, 1);
newArray[0] = byte.Parse("0");
bytes= newArray;
}
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;
}
This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
How do you convert Byte Array to Hexadecimal String, and vice versa, in C#?
C# byte[] to hex string
I need to take this:
byte[] data = new byte[] { 1, 2, 3, 4 }
And turn it into something like this:
0x01020304
What is the best way to do this in C#?
StringBuilder sb = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
{
sb.AppendFormat("{0:x2}", b)
}
return sb.ToString();
For a single value:
String.Format("{0:X2}", value);
Depending on what the array represents you can then do some string concatenating to put all the bits together.