This question already has answers here:
c# how to add byte to byte array
(7 answers)
Closed 7 years ago.
I have a byte array which contains an image; I converted the image to byte array using this method:
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
This is the byte array:
Bitmap bmp = Image.FromFile("xxx");
byte[] buffer = ImageToByteArray(bmp);
Now I would like to add some minor minor information about the image in the byte array,such as the position it should be drawn to,etc.
How could it be done? Lets say i want to add these 2 values:1209,540.
First I don't think you can use these values 1209,540 since byte's max val is 255.
But if your values are between that range 0-255, why don't you add two bytes at the end of the array and when the conversion is to be made remove the last two values?
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Basically, why does this work?
System.IO.Stream stream = new MemoryStream();
int a = 4;
byte[] barray = new byte[a];
stream.Write(barray, 0, Marshal.SizeOf(a));
When this doesn't:
System.IO.Stream stream = new MemoryStream();
int a = 3;
byte[] barray = new byte[a];
stream.Write(barray, 0, Marshal.SizeOf(a));
This is the error I get:
The offset and length were greater than allowed for the matrix, or the number is greater than the number of elements from the index to the end of the source collection.
When using Marshel.SizeOf(a) you ask the size of the object in memory. Since a is an int the size is always 4.
When you say byte[] barray = new byte[a]; you say:
Create an array called barray of type byte with length a. Thus in the first code block you create an array of length 4 and in the second one you create an array of length 3. Both array's contain only zero's.
Then you say: write the (empty) array to the stream, starting at position 0 and with length 4 (Marshel.SizeOf(a) is always 4 because a is an int).
The first example array has a length of 4 and thus works. The second example only contains 3 bytes and thus the length is not correct and you get an error.
If you wish to save the int to the stream as bytes explicitly you could call BitConverter:
System.IO.Stream stream = new MemoryStream();
int a = 4;
byte[] barray = System.BitConverter.GetBytes(a);
stream.Write(barray, 0, Marshal.SizeOf(a));
Now you say: create an array called barray that is filled with the binary representation of integer variable a.
And then write that filled array to the stream.
This question already has answers here:
How do you convert a byte array to a hexadecimal string, and vice versa?
(53 answers)
How can I convert a hex string to a byte array? [duplicate]
(4 answers)
Closed 5 years ago.
I used the following code to convert a bytes array to a string:
byte[] saltBytes;
// ... filling the array with some values
for (int i = 0; i < saltBytes.Length; i++)
{
builder.Append(saltBytes[i].ToString("x2"));
}
string salt = builder.ToString();
Now, I would like to revert this process and convert my string to a bytes array. I was reading this question: Converting string to byte array in C#.
The answer mentions:
If you already have a byte array then you will need to know what type
of encoding was used to make it into that byte array.
I'm not sure about the encoding used in the snippet I posted. Does this have to do with the ToString("x2") part?
This question already has answers here:
Converting 2 bytes to Short in C#
(3 answers)
Closed 6 years ago.
I am trying to read bytes.
Bytes:
0x83 0xF6
Those bytes are equal to 33782.
I need a code to convert those bytes to 33782.
I have tried using this code:
Encoding.ASCII.GetString(new byte[] { 0x83, 0xF6 });
But it give this as a response: ??
You are using the wrong Conversion, converting this byte array with ASCII String will not give the correct result. The reason you get ?? is because the values 0xF6, 0x83 lie outside the ASCII Table which is used to make the conversion in your case.
You should use BitConverter.ToUInt16()
var number = BitConverter.ToUInt16(new byte[] { 0xF6, 0x83}, 0).ToString();
You have to reverse the byte array first though for the Little/Big Endians.
Perhaps this?
(0x83 * 256 + 0xF6).ToString()
I am trying to write an Encoded file.The file has 9 to 12 bit symbols. While writing a file I guess that it is not written correctly the 9 bit symbols because I am unable to decode that file. Although when file has only 8 bit symbols in it. Everything works fine. This is the way I am writing a file
File.AppendAllText(outputFileName, WriteBackContent, ASCIIEncoding.Default);
Same goes for reading with ReadAllText function call.
What is the way to go here?
I am using ZXing library to encode my file using RS encoder.
ReedSolomonEncoder enc = new ReedSolomonEncoder(GenericGF.AZTEC_DATA_12);//if i use AZTEC_DATA_8 it works fine beacuse symbol size is 8 bit
int[] bytesAsInts = Array.ConvertAll(toBytes.ToArray(), c => (int)c);
enc.encode(bytesAsInts, parity);
byte[] bytes = bytesAsInts.Select(x => (byte)x).ToArray();
string contentWithParity = (ASCIIEncoding.Default.GetString(bytes.ToArray()));
WriteBackContent += contentWithParity;
File.AppendAllText(outputFileName, WriteBackContent, ASCIIEncoding.Default);
Like in the code I am initializing my Encoder with AZTEC_DATA_12 which means 12 bit symbol. Because RS Encoder requires int array so I am converting it to int array. And writing to file like here.But it works well with AZTEC_DATA_8 beacue of 8 bit symbol but not with AZTEC_DATA_12.
Main problem is here:
byte[] bytes = bytesAsInts.Select(x => (byte)x).ToArray();
You are basically throwing away part of the result when converting the single integers to single bytes.
If you look at the array after the call to encode(), you can see that some of the array elements have a value higher than 255, so they cannot be represented as bytes. However, in your code quoted above, you cast every single element in the integer array to byte, changing the element when it has a value greater than 255.
So to store the result of encode(), you have to convert the integer array to a byte array in a way that the values are not lost or modified.
In order to make this kind of conversion between byte arrays and integer arrays, you can use the function Buffer.BlockCopy(). An example on how to use this function is in this answer.
Use the samples from the answer and the one from the comment to the answer for both conversions: Turning a byte array to an integer array to pass to the encode() function and to turn the integer array returned from the encode() function back into a byte array.
Here are the sample codes from the linked answer:
// Convert byte array to integer array
byte[] result = new byte[intArray.Length * sizeof(int)];
Buffer.BlockCopy(intArray, 0, result, 0, result.Length);
// Convert integer array to byte array (with bugs fixed)
int bytesCount = byteArray.Length;
int intsCount = bytesCount / sizeof(int);
if (bytesCount % sizeof(int) != 0) intsCount++;
int[] result = new int[intsCount];
Buffer.BlockCopy(byteArray, 0, result, 0, byteArray.Length);
Now about storing the data into files: Do not turn the data into a string directly via Encoding.GetString(). Not all bit sequences are valid representations of characters in any given character set. So, converting a random sequence of random bytes into a string will sometimes fail.
Instead, either store/read the byte array directly into a file via File.WriteAllBytes() / File.ReadAllBytes() or use Convert.ToBase64() and Convert.FromBase64() to work with a base64 encoded string representation of the byte array.
Combined here is some sample code:
ReedSolomonEncoder enc = new ReedSolomonEncoder(GenericGF.AZTEC_DATA_12);//if i use AZTEC_DATA_8 it works fine beacuse symbol size is 8 bit
int[] bytesAsInts = Array.ConvertAll(toBytes.ToArray(), c => (int)c);
enc.encode(bytesAsInts, parity);
// Turn int array to byte array without loosing value
byte[] bytes = new byte[bytesAsInts.Length * sizeof(int)];
Buffer.BlockCopy(bytesAsInts, 0, bytes, 0, bytes.Length);
// Write to file
File.WriteAllBytes(outputFileName, bytes);
// Read from file
bytes = File.ReadAllBytes(outputFileName);
// Turn byte array to int array
int bytesCount = bytes.Length * 40;
int intsCount = bytesCount / sizeof(int);
if (bytesCount % sizeof(int) != 0) intsCount++;
int[] dataAsInts = new int[intsCount];
Buffer.BlockCopy(bytes, 0, dataAsInts, 0, bytes.Length);
// Decoding
ReedSolomonDecoder dec = new ReedSolomonDecoder(GenericGF.AZTEC_DATA_12);
dec.decode(dataAsInts, parity);
This question already has answers here:
How to convert UTF-8 byte[] to string
(16 answers)
Closed 7 years ago.
I want to know how to convert a byte[] to string. I have variable K an integer array and pwd a byte[] hence the the code bellow is giving me errors?
public void temp()
{
int[] k = new int[256];
byte[] pwd;
int temp = 50;
k[tmp] = pwd[(tmp % Convert.ToString((string)pwd).Length)];
}
Presumably if it's in a byte array, it's encoded. If you know what encoding, simply call GetString on the encoding. For example, if it's UTF8 encoded:
Encoding.UTF8.GetString(pwd);