It is posible to add string with byte? [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How to append string and byte array?
String array="$MT!BOOTLOADER";
Byte[] hexdecimal={0x01,0x05,0x0036};

You probably want to do something low level, so in the end you won't need a string but a byte[], so:
string array="$MT!BOOTLOADER";
byte[] hexdecimal={0x01,0x05,0x36};
byte[] bytesOrig = Encoding.ASCII.GetBytes(array);
byte[] bytesFinal = bytesOrig;
Array.Resize(ref bytesFinal, bytesFinal.Length + hexdecimal.Length);
Array.Copy(hexdecimal, 0, bytesFinal, bytesOrig.Length, hexdecimal.Length);
// bytesFinal contains all the bytes
I'm using Encoding.ASCII because your signature is ASCII (and normally signatures are ASCII)
equivalent code, but little different (we preallocate the array with the right size, by doing two calls to Encoding.ASCII methods)
string array="$MT!BOOTLOADER";
byte[] hexdecimal={0x01,0x05,0x36};
int count = Encoding.ASCII.GetByteCount(array);
byte[] bytes = new byte[count + hexdecimal.Length];
Encoding.ASCII.GetBytes(array, 0, array.Length, bytes, 0);
Array.Copy(hexdecimal, 0, bytes, count, hexdecimal.Length);
// bytes contains all the bytes

Use this function for converting string to byte and byte to string.
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
static string GetString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}

Related

Can read length delimited file in Julia but not in Rust [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
In julia I am able to read the first 4 bytes from the file using this code. (It is the length of the message to read)
# Read the length in first 4 bytes
msglen = read(R.buffer, UInt32)
# Then read up to that length
bytes = read(R.buffer, msglen)
But when I try to read the same file in Rust the length value comes up way too big:
let mut f = std::fs::File::open("../20181002.bytes").unwrap();
let mut buf = Vec::new();
f.read_to_end(&mut buf).expect("file reading failed");
let mut dst = [0u8; 4];
let mut read_index = 0usize;
// select first 4 bytes of buf and clone into dst
dst.clone_from_slice(&buf[read_index..(read_index+4)]);
println!("Dst: {:?}", &buf[read_index..(read_index+4)]);
let length = u32::from_le_bytes(dst);
println!("Len: {}", length);
Dst: [31, 139, 8, 0]
Len: 559903
I think the first 4 bytes should be 1f8b 0800 0000 0000
If its of help, here is how its written in C#:
public static void Write(Stream stream, byte[] bytes)
{
var lengthBuffer = BitConverter.GetBytes(bytes.Length);
// Write object length.
stream.Write(lengthBuffer, offset: 0, count: 4);
// Write object.
stream.Write(bytes, offset: 0, count: bytes.Length);
}
1f8b is the magic number for gzip encoded files. Sorry to waste your time - leaving the code up in case it interests anyone.

How does stream.write work? [closed]

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.

Read and write more than 8 bit symbols

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);

how to convert byte to string in C# [duplicate]

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);

How to define a byte array use the string style in .net?

I want define a byte array like "\x90<>",
I can only define it use numbers
byte[] a = new byte[] { 0x90, 0x3c, 0x3e };
but it's not readable and cost more time to write,
Can I do something like this in .net?
byte[] a = '\x90<>';
Edited.
I'm ask this because in c and c++ I can actually define a byte array by
char myvar[] = "\x90<>"; or char *myvar= "\x90<>";
they are equals new byte[] { 0x90, 0x3c, 0x3e} on c#.
A string is an array of chars, where a char is not a byte in the .Net.
You can't define bytes with a string and you can't do this in easy way, you must implement your own convertor methods and use it with that.
Check this out:
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
static string GetString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}
Try converting it to a char array in the declaration. The escaped characters will be correctly processed into a single char and the unescaped characters will be split into individual characters.
Then you can cast each element in the array as a byte. You could use LINQ to make it easy:
var bytes = "\x90<>".ToCharArray().Select(b => (byte)b);
foreach(var myByte in bytes){
Console.WriteLine(string.Format("0x{0:x2}", myByte));
}
I believe this gives you the correct output of 0x90, 0x3c, 0x3e
Edit
I'm sure there will be some issue with encoding here, but none was specified in the question.
Extra Edit
The code above will give you an IEnumerable<byte>. To get the actual byte[] you want, just call
bytes.ToArray();
Convert to byte array as this.
string source = "\x90<>";
byte[] bytes = Encoding.Default.GetBytes(source);

Categories

Resources