Converting byte array to string in C# [duplicate] - c#

This question already has answers here:
How to convert byte array to string [duplicate]
(4 answers)
Closed 9 years ago.
Is there an easy way to convert a byte array to a string so the following unit test passes? I can't find an encoding that works for all values.
[TestMethod]
public void TestBytToString()
{
byte[] bytArray = new byte[256];
for (int i = 0; i < bytArray.Length; i++)
{
bytArray[i] = (byte)i;
}
string x = System.Text.Encoding.Default.GetString(bytArray);
for (int i = 0; i < x.Length; i++)
{
int y = (int)x[i];
Assert.AreEqual(i, y);
}
}

The System.Text.Encoding.UTF8 should do a trick for you.

string x = Encoding.UTF8.GetString(bytArray, 0, bytArray.Length);

var str = System.Text.Encoding.Default.GetString(bytArray);

As far as i know everthing above value 127 in byte is considered a negative number and as char can only take positive values it results with an unknown char in every encoding you take.
You might want to convert the byte array to unsigned short (ushort) and then to string...

This worked:
[TestMethod]
public void TestBytToString()
{
byte[] bytArray = new byte[256];
ushort[] usArray = new ushort[256];
for (int i = 0; i < bytArray.Length; i++)
{
bytArray[i] = (byte)i;
}
string x = System.Text.Encoding.Default.GetString(bytArray);
for (int i = 0; i < x.Length; i++)
{
int y = System.Text.Encoding.Default.GetBytes(x.Substring(i, 1))[0];
Assert.AreEqual(i, y);
}
}

Related

How to solve Check array index and length?

Error message: System.ArgumentException: 'Destination array is not long enough to copy all the items in the collection. Check array index and length.'
public static string PassConv(string Password)
{
int iLoop;
int iL;
int iTotal;
int iValue;
string sPassConv;
iL = 3;
iTotal = 0;
for (iLoop = 1; iLoop <= Password.Length; iLoop++) {
string sNo = Password.Substring(iLoop-1,1);
byte[] asciiBytes = Encoding.ASCII.GetBytes(sNo);
iValue = BitConverter.ToInt32(asciiBytes, 0); ---->**Error**
iTotal = iTotal + iValue * (iL + iLoop - 1);
sPassConv = iTotal.ToString();
}
return sPassConv;
}
Please Help
Thank
I try to reach your idea because of so many redundancy codes. By using:
SubString exports each character even Encoding.ASCII.GetBytes can return all byte array from these characters
BitConverter expected of 4-byte binary input as well
https://learn.microsoft.com/en-us/dotnet/api/system.bitconverter.toint32 and seem this function is no help at all
Declare iLoop = 1 but inside loop does iLoop - 1
sPassConv gets value from iTotal so many times, should put outside the loop
Quick fix from your code:
public static string PassConv(string Password)
{
int iLoop;
int iL;
int iTotal;
int iValue;
string sPassConv = "";
iL = 3;
iTotal = 0;
for (iLoop = 1; iLoop <= Password.Length; iLoop++)
{
string sNo = Password.Substring(iLoop - 1, 1);
iValue = Encoding.ASCII.GetBytes(sNo)[0];
iTotal = iTotal + iValue * (iL + iLoop - 1);
sPassConv = iTotal.ToString();
}
return sPassConv;
}
A little bit refactor
public static string PassConv2(string Password, int iL = 3)
{
int iTotal = 0;
var bytes = Encoding.ASCII.GetBytes(Password);
for (var iLoop = 0; iLoop < bytes.Length; iLoop++)
{
// bytes[iLoop] = iValue
iTotal += bytes[iLoop] * (iL + iLoop);
}
return iTotal.ToString();
}
This function is need to be improved because it does loop 2 times, first to bytes and second to calculate. Since every character can convert to ASCII even Extended ASCII, so we could cast it directly. PassConv3 gives more exact when input is Unicode such as "Áaa", the Encoding.ASCII.GetByteswill cast as "?aa" with '?' represents 63 ASCII
public static string PassConv3(string Password, int iL = 3)
{
int iTotal = 0;
for (var iLoop = 0; iLoop < Password.Length; iLoop++)
{
iTotal += Password[iLoop] * (iL + iLoop);
}
return iTotal.ToString();
}
And the result
public static void MainFunc()
{
Console.WriteLine(PassConv("ABCD")); // 1202
Console.WriteLine(PassConv2("ABCD")); // 1202
Console.WriteLine(PassConv3("ABCD")); // 1202
}
Hope it helps !

Converting from a string to hex array

I have a problem when converting a char to hex value the code below works correctly when the char is a number but it's throw exception when the char is a latter
System.FormatException: 'Input string was not in a correct format
Code:
public byte[,] get_state(string plainText)
{
char[] cplainText = plainText.ToCharArray();
byte[,] state = new byte[4, 4];
plainText = plainText.Remove(0, 2);
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j+=2)
{
string sub = plainText.Substring((i * 4 + j), 2);
state[i, j] = Convert.ToByte(sub);
}
}
return state;
}
The input string was "0x3243F6A8885A308D313198A2e0370734" and the exception across when the iteration of "F6"
Convert.ToByte();
It says in the overload that it only accepts numbers in string format.
You have to think about if you use the right method, or convert it beforehand.

Converting a String to a String of Binary

My goal is to be able to convert a string into binary code that is still a string. I am able to turn the string into byte[] but not back to a string without decoding it.
You can use the Convert method for that:
byte [] bytesToEncode = Encoding.UTF8.GetBytes (inputText);
string encodedText = Convert.ToBase64String (bytesToEncode);
If you can encode/decode a byte, e.g.
private static String ToBinary(Byte value) {
StringBuilder Sb = new StringBuilder(8);
Sb.Length = 8;
for (int i = 0; i < 8; ++i) {
Sb[7 - i] = (Char) ('0' + value % 2);
value /= 2;
}
return Sb.ToString();
}
private static Byte FromBinary(String value) {
int result = 0;
for (int i = 0; i < value.Length; ++i)
result = result * 2 + value[i] - '0';
return (Byte) result;
}
You can easily encode/decode a whole string:
// Encoding...
String source = "abc";
// 011000010110001001100011
String result = String.Join("", UTF8Encoding.UTF8.GetBytes(source).Select(x => ToBinary(x)));
...
// Decoding...
List<Byte> codes = new List<Byte>();
for (int i = 0; i < result.Length; i += 8)
codes.Add(FromBinary(result.Substring(i, 8)));
// abc
String sourceBack = UTF8Encoding.UTF8.GetString(codes.ToArray());
use
string str = "Welcome";
byte []arr = System.Text.Encoding.ASCII.GetBytes(str);

C# error: Cannot Convert 'string[]' to 'string'

I am trying to write some C# code for Unity that will read from a text file, store each line in a string array, and then convert it to a 2D char array.
The error occurs at:
void ReadFile()
{
StreamReader read = new StreamReader(Application.dataPath + "/Maze1.txt");
int length = read.ReadLine().Length;
maze = new string[length, length];
line = new string[length];
while(!read.EndOfStream)
{
for (int i = 0; i <= length; i++)
{
line[i] = read.ReadLine();
}
for( int i = 0; i <= length; i++)
{
for( int j = 0; j <= length; j++)
{
maze[i,j] = line[i].Split(','); // <---This line is the issue.
}
}
}
}
The Exact error I am getting is:
Cannot Implicitly convert type 'string[]' to 'string'
What does this error mean and how do I fix the code?
I have a feeling you meant to do this:
for( int i = 0; i <= length; i++)
{
var parts = line[i].Split(',');
for( int j = 0; j <= length; j++)
{
maze[i,j] = parts[j];
}
}
As error says maze[i,j] will take a string but line[i].Split(','); would return a string[].
The better data structure for the maze is in your case an array of arrays, instead of the 2d array. So you can assign the result of the split operation directly without the extra copy:
StreamReader read = new StreamReader(Application.dataPath + "/Maze1.txt");
string firstLine = read.ReadLine();
int length = firstLine.Length;
string[][] maze = new string[length][];
maze[0] = firstLine.Split(',');
while(!read.EndOfStream)
{
for (int i = 1; i < length; i++)
{
maze[i] = read.ReadLine().Split(',');
}
}
You can then access the maze similar to the 2d array:
var aMazeChar = maze[i][j];

How do I parse a PolyPolygon16 metafile record out of a byte[] c#

I need a little help in defining the following Windows GDI type in C#. I have the data in the form of a byte[] in C#, and I need to somehow marshal or cast it as the following in C#.
This is the type:
http://java.freehep.org/vectorgraphics/apidocs/org/freehep/graphicsio/emf/gdi/PolyPolygon16.html
http://msdn.microsoft.com/en-us/library/cc230665%28PROT.10%29.aspx
Edit: I have been able to get this far, close but not quite:
UInt32 rectLeft = BitConverter.ToUInt32(dataArray, 0);
UInt32 rectTop = BitConverter.ToUInt32(dataArray, 4);
UInt32 rectRight = BitConverter.ToUInt32(dataArray, 8);
UInt32 rectBottom = BitConverter.ToUInt32(dataArray, 12);
UInt32 rectNumberOfPolygons = BitConverter.ToUInt32(dataArray, 16);
// Number of points in each polygon
int l_nIndex = 20;
UInt32[] lengths = new UInt32[rectNumberOfPolygons];
for (int i = 0; i < lengths.Length; i++)
{
lengths[i] = BitConverter.ToUInt32(dataArray, l_nIndex);
l_nIndex += 4;
}
// Extract points
foreach (int l_nPolygonLength in lengths)
{
List<Point> l_lstPoints = new List<Point>();
for (int i = 0; i < l_nIndex + l_nPolygonLength; i++)
{
UInt16 pointX = BitConverter.ToUInt16(dataArray, l_nIndex);
UInt16 pointY = BitConverter.ToUInt16(dataArray, l_nIndex + 2);
l_lstPoints.Add(new Point((int)pointX, (int)pointY));
l_nIndex += 4;
}
}
RectL Object:
public static Rectangle ReadRectangle32(this BinaryReader reader)
{
// Left (4 bytes)
int left = reader.ReadInt32();
// Top (4 bytes)
int top = reader.ReadInt32();
// Right (4 bytes)
int right = reader.ReadInt32();
// Bottom (4 bytes)
int bottom = reader.ReadInt32();
return Rectangle.FromLTRB(left, top, right, bottom);
}
PointS Object:
public static Point ReadPoint16(this BinaryReader reader)
{
// x (2 bytes)
int x = reader.ReadUInt16();
// y (2 bytes)
int y = reader.ReadUInt16();
return new Point(x, y);
}
EMR_POLYPOLYGON16 Record (without type and size):
public static PolyPolygon ReadPolyPolygon16(this BinaryReader reader)
{
// Bounds (16 bytes)
Rectangle bounds = reader.ReadRectangle32();
// NumberOfPolygons (4 bytes)
int numberOfPolygons = reader.ReadInt32();
// Count (4 bytes)
int count = reader.ReadInt32();
// PolygonPointCount (variable):
// A NumberOfPolygons length array of 32-bit unsigned integers
var polygonPointCount = new int[numberOfPolygons];
for (int i = 0; i < polygonPointCount.Length; i++)
{
polygonPointCount[i] = reader.ReadInt32();
}
// aPoints (variable):
// A Count length array of WMF PointS objects
var points = new Point[count];
for (int i = 0; i < points.Length; i++)
{
points[i] = reader.ReadPoint16();
}
return new PolyPolygon(bounds, numberOfPolygons, polygonPointCount, points);
}
Usage:
byte[] buffer;
using (var stream = new MemoryStream(buffer))
using (var reader = new BinaryReader(stream))
{
var polypolygon = reader.ReadPolyPolygon16();
}
(Untested)
That seems to be the method signature of Windows GDI function (not a type). It's second argument is a pointer to an array of points, you want to have drawn. Third argument is a pointer to an array of integers specifying how many points there are in each polygon, and the last argument is the number of polygons.
I could not find a Windows GDI function exactly named PolyPolygon16 when searching on Google, but I did find this.

Categories