Converting List<string> to byte[] - c#

How can I take a List and turn it into a byte array.
I thought there might be some clever LINQ options for it but am unsure eg/List.ForEach

Depends on which encoding you want to use to convert the string to a byte[] but here's a sample for ASCII. It can be substituted for pretty much any encoding type
List<string> data = ...
byte[] dataAsBytes = data
.SelectMany(s => Text.Encoding.ASCII.GetBytes(s))
.ToArray();

with a simple foreach loop:
(pseudocode)
List<byte[]> bytes = new List<byte[]>();
ForEach string el in somelist
{
byte[] arr;
System.Text.UTF8Encoding encoding=new System.Text.UTF8Encoding();
arr = encoding.GetBytes(el);
bytes.add(arr);
}

Related

C# equivalent to parse cryptojs

I'm trying to create C# that does this in CryptoJS
var hash = CryptoJS.HmacSHA512(msg, key);
var crypt = CryptoJS.enc.Utf8.parse(hash.toString());
var base64 = CryptoJS.enc.Base64.stringify(crypt);
My question is in the second statement where hash variable is put into a string then parsed.
Is there an equivalent in C#? Once parsed how do you encode the result into Utf8.
Thanks
I'm not 100% if I understand exactly which piece you are looking for here. But there is no such thing as a UTF8 System.String in C#. However when you write a string to a stream you can choose the encoding of the bytes in the stream to be UTF8
For example by passing that encoding as an option to a StreamWriter.
using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8)) {
writer.Write(text);
}
My boss find the answer to this. The difference is that before you return the base64 string using C# you have to change the bytes into hexadecimal.
var encoder = new UTF8Encoding();
byte[] keyBytes = encoder.GetBytes(key);
var newlinemsg = action + "\n" + msg;
byte[] messageBytes = encoder.GetBytes(newlinemsg);
byte[] hashBytes = new HMACSHA512(keyBytes).ComputeHash(messageBytes);
var hexString = ToHexString(hashBytes);
var base64 = Convert.ToBase64String(encoder.GetBytes(hexString));

Reverse Convert.ToBase64String(byte[] array)

In example
string newString = Convert.ToBase64String(byte[] array)
How would I go about converting newString to get a byte[] (byte array)?
Convert.FromBase64String(newString)
byte[] data = Convert.FromBase64String(newString);
string decodedString = Encoding.UTF8.GetString(data);
byte[] array= Convert.FromBase64String(newString);

Convert a string to byte[] for socket

I am writing a simple ftp client with c#.
I am not pro in c#. Is there any way to convert string to byte[] and write it to the socket?
for example for introducing username this is the socket content:
5553455220736f726f7573680d0a
and ASCII equivalent is:
USER soroush
I want a method to convert string. Something like this:
public byte[] getByte(string str)
{
byte[] ret;
//some code here
return ret;
}
Try
byte[] array = Encoding.ASCII.GetBytes(input);
// C# to convert a string to a byte array.
public static byte[] StrToByteArray(string str)
{
Encoding encoding = Encoding.UTF8; //or below line
//System.Text.UTF8Encoding encoding=new System.Text.UTF8Encoding();
return encoding.GetBytes(str);
}
and
// C# to convert a byte array to a string.
byte [] dBytes = ...
string str;
Encoding enc = Encoding.UTF8; //or below line
//System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
str = enc.GetString(dBytes);

Compressing and decompressing a string yields only the first letter of the original string?

I'm compressing a string with Gzip using this code:
public static String Compress(String decompressed)
{
byte[] data = Encoding.Unicode.GetBytes(decompressed);
using (var input = new MemoryStream(data))
using (var output = new MemoryStream())
{
using (var gzip = new GZipStream(output, CompressionMode.Compress, true))
{
input.CopyTo(gzip);
}
return Convert.ToBase64String(output.ToArray());
}
}
and decompressing it with this code:
public static String Decompress(String compressed)
{
byte[] data = Convert.FromBase64String(compressed);
using (MemoryStream input = new MemoryStream(data))
using (GZipStream gzip = new GZipStream(input, CompressionMode.Decompress))
using (MemoryStream output = new MemoryStream())
{
gzip.CopyTo(output);
StringBuilder sb = new StringBuilder();
foreach (byte b in output.ToArray())
sb.Append((char)b);
return sb.ToString();
}
}
When I use these functions in this sample code, the result is only the letter S:
String test = "SELECT * FROM foods f WHERE f.name = 'chicken';";
String com = Compress(test);
String decom = Decompress(com);
Console.WriteLine(decom);
If I debug the code, I see that the value of decom is
S\0E\0L\0E\0C\0T\0 \0*\0 \0F\0R\0O\0M\0 \0f\0o\0o\0d\0s\0 \0f\0 \0W\0H\0E\0R\0E\0 \0f\0.\0n\0a\0m\0e\0 \0=\0 \0'\0c\0h\0i\0c\0k\0e\0n\0'\0;\0
but the value displayed is only the letter S.
These lines are the problem:
foreach (byte b in output.ToArray())
sb.Append((char)b);
You are interpreting each byte as its own character, when in fact that is not the case. Instead, you need the line:
string decoded = Encoding.Unicode.GetString(output.ToArray());
which will convert the byte array to a string, based on the encoding.
The basic problem is that you are converting to a byte array based on an encoding, but then ignoring that encoding when you retrieve the bytes. As well, you may want to use Encoding.UTF8 instead of Encoding.Unicode (though that shouldn't matter, as long as the encodings match up.)
In your compress method replace Unicode with UTF8:
byte[] data = Encoding.UTF8.GetBytes(decompressed);

how to convert from string to byte[] [duplicate]

I have the following code:
string s = "2563MNBJP89256666666685755854";
Byte[] bytes = encoding.GetBytes(s);
string hex = "";
foreach (byte b in bytes)
{
int c=b;
hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(c.ToString()));
}
It prints the hex values . How can I add it in a vector ob bytes like this?
new byte [0x32,0x35..]
In hex I have : 323536....and so on. The next step is to add then in a byte[] vector in the following format 0x32,0x35..and so on; How to do this?
THX
Isn't bytes already the list of bytes you want?
C#: System.Text.Encoding.ASCII.GetBytes("test")
For C# you could try
System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(strVar);//strVar is the string variable
in C# you can use Encoding.GetBytes Method

Categories