This question already has answers here:
byte[] to hex string [duplicate]
(19 answers)
Closed 8 years ago.
I'm trying to create a simple Hex Editor with C#.
For this I'm writing the file into an byte-array, which works fine. But as soon as I put out the bytes to a Textbox in form of a string, the overall performance of the program becomes pretty bad. For example a 190kb file takes about 40 seconds, till it is displayed in the textbox. While that the program is not responding.
The function:
void open()
{
fullstring = "";
OpenFileDialog op = new OpenFileDialog();
op.ShowDialog();
file = op.FileName;
byte[] fileB = File.ReadAllBytes(file);
long b = fileB.Length;
for (int i = 0; i < fileB.Length; i++)
{
fullstring = fullstring + fileB[i].ToString("X") + " ";
}
textBox9.Text = fullstring;
}
Is there a way to improve performance in this function?
Take a look at this post How do you convert Byte Array to Hexadecimal String, and vice versa?
You can use the code there to output your byte array to text file. One problem you have in your code is that you are using String concatenation instead of StringBuilder. It is better to use StringBuilder otherwise the performance degrades.
Related
The task is to take a picture, read all its bytes and then write additional 15 zero bytes after each non-zero byte from original file. Example: it was B1,B2,...Bn and after it must be B1,0,0,..0,B2,0,0..,Bn,0,0..0. Then I need to save/replace new picture. In general I assume I can use something like ReadAllBytes and create an array of bytes, then create new byte[] array and take one byte from file, then write 15 zero bytes, then take second byte and etc. But how can I be sure that it is working correctly? I'm not familiar with working with bytes and if I try to print bytes that I've read from file it shows some random symbols that don't make any sense which leaves the question: am I doing it right? If possible, please direct me to right approach and the functions that I need to use to achieve it, thanks in advance!
See How to convert image to byte array for how to read the image.
It seems that you'd like to be able to visually see the data. For debugging purposes, you can show each byte as a hex string which will allow you to "see" the hex values of each element of your array.
public string GetBytesAsHexString(byte[] bArr)
{
StringBuilder sb = new StringBuilder();
if (bArr != null && bArr.Length > 0)
{
for (int i = 0; i < bArr.Length; i++)
{
sb.AppendFormat("{0}{1}", bArr[i].ToString("X"), System.Environment.NewLine);
//sb.AppendFormat("{0}{1}", bArr[i].ToString("X2"), System.Environment.NewLine);
//sb.AppendFormat("{0}{1}", bArr[i].ToString("X4"), System.Environment.NewLine);
}
}
return sb.ToString();
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to read a file (>150 mb) and I need to read the binary representation of that file.
The file type is a .MP4.
I am trying to use this:
string.Join("-", x.Select(byt => Convert.ToString(byt, 2).PadLeft(8, '0')));
but the problems are:
1) It is too slow
2) It uses a lot of RAMs memory
If I read the raw bytes with
File.ReadAllBytes(path);
How Can I do that without having to convert the file into a string (method below)?
When working with big files like in your case, it would be better to just view a small part of the file (It's not like you can show the entire file at once anyhow).
Some Streams (like the FileStream) have the ability to Seek a certain position, which you can use to set your starting position.
if(position > _stream.Length)
throw new IndexOutOfRangeException();
if (position + length > _stream.Length)
length = (int) (_stream.Length - position);
_stream.Seek(position, SeekOrigin.Begin);
_stream.Read(buffer, 0, length);
The conversion to binary isn't that hard eiter, depending on the bit order you want, you'll probably have to reverse this (this is highest bit left 1 = 00000001). To gain some performance when building the string, use a StringBuilder instead of just concating strings with += or +.
public string ToBinary(byte value)
{
string result = "";
for (int i = 0; i < 8; i++)
{
result = value%2 + result;
value /= 2;
}
return result;
}
private string ToBinary(byte[] values)
{
StringBuilder builder = new StringBuilder();
int column = 0;
foreach (byte value in values)
{
builder.Append(ToBinary(value) + " ");
column++;
if (column == 8)
{
builder.AppendLine();
column = 0;
}
}
return builder.ToString();
}
Can can then eiter use it in a console application
https://dotnetfiddle.net/GVLm27
or put those two together with a TextBox and a ScrollBar and you have a good starting point:
ong position = (long) scrollBar1.Value;
byte[] data = new byte[128];
_file.GetSection(data, position, data.Length);
textBox1.Text = ToBinary(data);
After all those comments on your question I hope the original title is still what you are after
C# Fastest way to read binary representation of data
This question already has answers here:
Convert integer to hexadecimal and back again
(11 answers)
Closed 8 years ago.
This is a small snippet of the code I have written in Visual Studio.
I need to convert the int add into an hex value (later into a string) as I am accessing the memory of a uC. But when I view the variable during debugging it displays it as a string "add16". What could I be doing wrong?
for (int add = 0; add <= 0xfffff; )
{
for (int X = 0; X <= 15; X++)
{
string address = add.ToString("add16");
addr = Convert.ToString(address);
port.WriteLine(String.Format("WRBK:{0}:{1}", addr, parts[X]));
add++;
}
}
There is a simple and very convenient method that takes an integer and returns a representation of it as a string in hexadecimal notation
string address = Convert.ToString(add, 16);
So, perhaps, your internal loop could be rewritten as
port.WriteLine(String.Format("WRBK:{0}:{1}", Convert.ToString(add++, 16), parts[X]));
and using the standard numeric format strings specifiers reduced to
port.WriteLine(String.Format("WRBK:{0:X}:{1}", add++, parts[X]));
You can tell .NET's String.Format to use hex output for the integer, eliminating any code to hex conversion, use:
port.WriteLine(String.Format("WRBK:{0:X}:{1}", add, parts[X]));
This question already has answers here:
How to read a large (1 GB) txt file in .NET?
(9 answers)
How to read a specific part in text file?
(2 answers)
Closed 8 years ago.
There's a big text file. And I cannot read it with File.ReadAllText() method. How to read it piece by piece in C#?
Try Something like this.
Here i read the file in blocks of 2 megabytes.
This will reduce the load of loading file and reading as it reads in block of 2 megabytes.
You can change the size if you want from 2 megabytes to what so ever.
using (Stream objStream = File.OpenRead(FilePath))
{
// Read data from file
byte[] arrData = { };
// Read data from file until read position is not equals to length of file
while (objStream.Position != objStream.Length)
{
// Read number of remaining bytes to read
long lRemainingBytes = objStream.Length - objStream.Position;
// If bytes to read greater than 2 mega bytes size create array of 2 mega bytes
// Else create array of remaining bytes
if (lRemainingBytes > 262144)
{
arrData = new byte[262144];
}
else
{
arrData = new byte[lRemainingBytes];
}
// Read data from file
objStream.Read(arrData, 0, arrData.Length);
// Other code whatever you want to deal with read data
}
}
This question already has answers here:
How can you encode a string to Base64 in JavaScript?
(33 answers)
Closed 9 years ago.
I have byte array and I can convert this usin Convert.ToBase64String() method in c#.
I wrote equivalent of this method in javascript like below. But the result is different.
in c#:
byte[] data = ...
Convert.ToBase64String(data)
in js
function GetStringFromByteArray(array) {
var result = "";
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < array[i].length; j++)
result += String.fromCharCode(array[i][j]);
}
return result;
}
How can I succeed this in js?
Yes, the result is different, because the Javascript function doesn't do base64 encoding at all.
The base64 encoded data contains six bits of information per character, so the eight bits of a character code is spread out over two characters in the encoded data.
To encode the data, you have to regroup the bits in the bytes into six bit groups, then you can convert each group into a base64 character.
See: Base64
You can use this javascript library