write hex data to file at specific address c# - c#

I need help to write hex data AB at adress 0x0156 in binary file in c#.
What i used BinaryWriter gives wrong data 00.
BinaryWriter bw = new BinaryWriter(File.OpenWrite(path));
bw.Write("AB");
bw.Dispose();

If you need to write it at address 0x156 you need to move there first using the Seek method. You also need to write a byte value rather than a string.
BinaryWriter bw = new BinaryWriter(File.OpenWrite(path));
bw.Seek(0x156,SeekOrigin.Begin);
bw.Write((byte)0xab);
bw.Dispose();
If the file does not exist, or is shorter than 343 bytes, it will be padded with 0 values up to the 342nd byte.
If you want to write a number of bytes starting from a particular location you could do something like this :
int StartLocation = 0x202;
int EndLocation = 0x30b;
byte ValueToWrite = 0xFF;
BinaryWriter bw = new BinaryWriter(File.OpenWrite(path));
bw.Seek(StartLocation,SeekOrigin.Begin);
for (int CurLocation = StartLocation; CurLocation <= EndLocation; CurLocation++)
bw.Write(ValueToWrite);
bw.Dispose();
Another way would be
int StartLocation = 0x202;
int EndLocation = 0x30b;
byte ValueToWrite = 0xFF;
byte [] ByteArray = new byte[EndLocation-StartLocation+1];
for (int i = 0; i < ByteArray.Length; i++)
ByteArray[i] = ValueToWrite;
BinaryWriter bw = new BinaryWriter(File.OpenWrite(path));
bw.Seek(StartLocation,SeekOrigin.Begin);
bw.Write(ByteArray);
bw.Dispose();

Related

converting string to byte array in c# getting zeros in bytes

i am using below code to read data in a .key extension file to byte array, i am getting 16 bytes output but all bytes are zeros.
System.IO.StreamReader myFile = new System.IO.StreamReader(Server.MapPath("ELECTRI.KEY"));
string myString = myFile.ReadLine();
string str = myString;
//string str = myString.Substring(0, myString.Length - 2);
BitArray bit = new BitArray(str.Length);
for (int i = 0; i < str.Length; i++)
{
if (str.Substring(i, 1) == "1")
{
bit[i] = true;
}
else
{
bit[i] = false;
}
}
int numBytes = bit.Count;
if (bit.Count % 8 != 0) numBytes++;
keyyy = new byte[numBytes];
keyyy = new byte[numBytes];
This sentence means initializing keyyy with new byte[numBytes], so all bytes are zeros. You have to assign each
Here is the code you need to fill the array
int numBytes = bit.Count;
if (bit.Count % 8 != 0) numBytes++;
keyyy = new byte[numBytes];
bit.CopyTo(keyyy, 0);
EDIT
byte[] keyyy = File.ReadAllBytes("ELECTRI.KEY");
I think if I understand your problem correctly now, it is a simple as doing this!
Here is another way you could approach the problem:
string str = "1111111100000000";
byte[] keyyy = new byte[str.Length / 8]
.Select((b, index) => Convert.ToByte(str.Substring(index * 8, 8), 2)).ToArray();
This statement splits the string into groups of 8 characters (ignoring remainders) using Substring. Each string of 8 characters (i.e. 11111111) is then converted into a byte using Convert.ToByte. The paramter 2 in Convert.ToByte let's the method know it is a base2 binary string.
Try this:
byte[] buffer;
using (StreamReader reader= new StreamReader("PATH HERE")) {
var input = reader.ReadToEnd();
buffer = Encoding.UTF8.GetBytes(input);
}
PS: This will read the whole file contents.

Convert uint[] to byte[] [duplicate]

This might be a simple one, but I can't seem to find an easy way to do it. I need to save an array of 84 uint's into an SQL database's BINARY field. So I'm using the following lines in my C# ASP.NET project:
//This is what I have
uint[] uintArray;
//I need to convert from uint[] to byte[]
byte[] byteArray = ???
cmd.Parameters.Add("#myBindaryData", SqlDbType.Binary).Value = byteArray;
So how do you convert from uint[] to byte[]?
How about:
byte[] byteArray = uintArray.SelectMany(BitConverter.GetBytes).ToArray();
This'll do what you want, in little-endian format...
You can use System.Buffer.BlockCopy to do this:
byte[] byteArray = new byte[uintArray.Length * 4];
Buffer.BlockCopy(uintArray, 0, byteArray, 0, uintArray.Length * 4];
http://msdn.microsoft.com/en-us/library/system.buffer.blockcopy.aspx
This will be much more efficient than using a for loop or some similar construct. It directly copies the bytes from the first array to the second.
To convert back just do the same thing in reverse.
There is no built-in conversion function to do this. Because of the way arrays work, a whole new array will need to be allocated and its values filled-in. You will probably just have to write that yourself. You can use the System.BitConverter.GetBytes(uint) function to do some of the work, and then copy the resulting values into the final byte[].
Here's a function that will do the conversion in little-endian format:
private static byte[] ConvertUInt32ArrayToByteArray(uint[] value)
{
const int bytesPerUInt32 = 4;
byte[] result = new byte[value.Length * bytesPerUInt32];
for (int index = 0; index < value.Length; index++)
{
byte[] partialResult = System.BitConverter.GetBytes(value[index]);
for (int indexTwo = 0; indexTwo < partialResult.Length; indexTwo++)
result[index * bytesPerUInt32 + indexTwo] = partialResult[indexTwo];
}
return result;
}
byte[] byteArray = Array.ConvertAll<uint, byte>(
uintArray,
new Converter<uint, byte>(
delegate(uint u) { return (byte)u; }
));
Heed advice from #liho1eye, make sure your uints really fit into bytes, otherwise you're losing data.
If you need all the bits from each uint, you're gonna to have to make an appropriately sized byte[] and copy each uint into the four bytes it represents.
Something like this ought to work:
uint[] uintArray;
//I need to convert from uint[] to byte[]
byte[] byteArray = new byte[uintArray.Length * sizeof(uint)];
for (int i = 0; i < uintArray.Length; i++)
{
byte[] barray = System.BitConverter.GetBytes(uintArray[i]);
for (int j = 0; j < barray.Length; j++)
{
byteArray[i * sizeof(uint) + j] = barray[j];
}
}
cmd.Parameters.Add("#myBindaryData", SqlDbType.Binary).Value = byteArray;

How to point to the particular index of BinaryStream?

I have a byte array consist of 32 bytes.
I want to read 4 bytes from index position 16 to 19.
How can i point binary reader to start reading from index 16.
I am trying these commands
byte[] trace ; // 32 byte array
using (FileStream s = File.OpenRead(filename))
using (BinaryReader r = new BinaryReader(s))
{
r.baseStream.Seek(position,SeekOrigin.Begin);
byte[] by = r.ReadBytes(4);
}
but i don't know what to put at position?
I think I got it (although your sample in the question is not very clear).
You have the byte array trace with 32 elements in it and you want to read 4 bytes starting with position 16.
Assuming that endianness is not a variable, you can use this to read the 4 bytes as an int value or byte array:
using(var memStream = new MemoryStream(trace))
{
//position the stream
using(var reader = new BinaryReader(memStream)
{
memStream.Seek(16, SeekOrigin.Begin);
var intValue = reader.ReadInt32();
memStream.Seek(16, SeekOrigin.Begin);
//now read a byte array
var byteArray = reader.ReadBytes(4);
}
}

"Parameter not valid" error when trying to save the image converted from byte

currently I am testing a script that tries to save an image file converted from a string of HEX, however, when I try to execute the Save command, parameter not valid appears.
// Some junk hex image data
string hexImgData = #"FFD8FFE000104A46494600010200006400640000FFFFD9";
// Call function to Convert the hex data to byte array
byte[] newByte = ToByteArray(hexImgData);
MemoryStream memStream = new MemoryStream(newByte);
// Save the memorystream to file
Bitmap.FromStream(memStream).Save("C:\\img.jpg");
// Function converts hex data into byte array
public static byte[] ToByteArray(String HexString)
{
int NumberChars = HexString.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(HexString.Substring(i, 2), 16);
}
return bytes;
}
Currently I am still in the process of looking what causes this, please advice.
As was mentioned in the comments, your bitmap format is wrong, all you have is some random hex data and the Bitmap.FromStream method has no idea what to do with it. If you look at this link which discusses how to create a bitmap file with a hex editor it discusses the BitmapHeader, BitmapInfoHeader, and the Pixel RGB Data. I was able to create a bitmap using your code by taking the data from their example and using it.
string bitmapHeader = "424D860000000000000036000000";
string bitmapInfoHeader = "280000000500000005000000010018000000000050000000C40E0000C40E00000000000000000000";
string pixelData = "0000FF0000FF0000FF0000FF0000FF000000FF0000FF0000FF0000FF0000FF000000FF0000FF0000FF0000FF0000FF000000FF0000FF0000FF0000FF0000FF000000FF0000FF0000FF0000FF0000FF00";
string hexImgData = bitmapHeader + bitmapInfoHeader + pixelData;
// Call function to Convert the hex data to byte array
byte[] newByte = ToByteArray(hexImgData);
MemoryStream memStream = new MemoryStream(newByte);
pictureBox1.Image = Bitmap.FromStream(memStream);
It seems you need convert incoming string from Base64 to byte array like this:
byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);

Need help Creating a big array from small byte arrays

i got the following code:
byte[] myBytes = new byte[10 * 10000];
for (long i = 0; i < 10000; i++)
{
byte[] a1 = BitConverter.GetBytes(i);
byte[] a2 = BitConverter.GetBytes(true);
byte[] a3 = BitConverter.GetBytes(false);
byte[] rv = new byte[10];
System.Buffer.BlockCopy(a1, 0, rv, 0, a1.Length);
System.Buffer.BlockCopy(a2, 0, rv, a1.Length, a2.Length);
System.Buffer.BlockCopy(a3, 0, rv, a1.Length + a2.Length, a3.Length);
}
everything works as it should. i was trying to convert this code so everything will be written into myBytes but then i realised, that i use a long and if its value will be higher then int.MaxValue casting will fail.
how could one solve this?
another question would be, since i dont want to create a very large bytearray in memory, how could i send it directry to my .WriteBytes(path, myBytes); function ?
If the final destination for this is, as suggested, a file: then write to a file more directly, rather than buffering in memory:
using (var file = File.Create(path)) // or append file FileStream etc
using (var writer = new BinaryWriter(file))
{
for (long i = 0; i < 10000; i++)
{
writer.Write(i);
writer.Write(true);
writer.Write(false);
}
}
Perhaps the ideal way of doing this in your case would be to pass a single BinaryWriter instance to each object in turn as you serialize them (don't open and close the file per-object).
Why don't you just Write() the bytes out as you process them rather than converting to a massive buffer, or use a smaller buffer at least?

Categories

Resources