Display string with misencoded characters as "?" C# - c#

I am currently working on an assignment where they asked me to recreate the memory viewer in visualstudio as a standalone program.
The issue I have been running into is the fact that Visual Studio uses some kind of non standard encoding with the extended ascii characterset (which is not in the standard Encoding class in C#).
If I print the string in the console some characters are represented as "?". This is fine and is considered a nonissue, the problem is that whenever I put sxaid string into the listbox for display, it filters out any "?" and just straight up removes them. Is there any way I can somehow make sure that either it displays a "?" or that I can fix the encoding?
Here are some screenshots from VS and my program as well as the console output
VS
My program
Console Output
EDIT: Woops I forgot to post the code...
public unsafe void FillForm(IntPtr startAddress)
{
listBox1.Items.Clear();
listBox2.Items.Clear();
listBox3.Items.Clear();
ReadMemory read = new ReadMemory();
List<MemoryModel> memoryModels = new List<MemoryModel>();
byte[] mem = read.ReadAddress(startAddress, DisplaySize);
char[] memChars = new char[mem.Length];
//dataGridView1.Columns.Add("0", "Address");
for (int i = 0; i < DisplaySize; i++)
{
//dataGridView2.Columns.Add(i.ToString(), i.ToString());
//dataGridView3.Columns.Add(i.ToString(), i.ToString());
}
for (int i = 0; i < DisplaySize; i++)
{
//listBox2.Items.Add();
//dataGridView3.Rows.Add();
listBox1.Items.Add("0x" + (startAddress + DisplaySize * i).ToString("X8"));
//dataGridView1[0, i].Value =
MemoryModel model = new MemoryModel();
for (int j = 0; j < DisplaySize; j++)
{
//memChars[j] = mem[j] == 255 || mem[j] == 127 || mem[j] < 33 ? '.' : (char)mem[j];
memChars[j] = mem[j] == 255 || mem[j] == 127 || mem[j] < 33 || ((char)mem[j]).ToString().Contains("\\u")? '.' : (char)mem[j];
Console.WriteLine(memChars[j] + " + " + mem[j]);
model.ByteStringAccordingToSize += mem[j].ToString("X2") + " ";
}
//convert to model
model.CharRepresentation = new string(memChars);
model.FirstByteAddress = "0x" + (startAddress + DisplaySize * i).ToString("X10");
Console.WriteLine("============ \n ROW: " + i);
Console.WriteLine(model.CharRepresentation);
Console.WriteLine("============");
memoryModels.Add(model);
mem = read.ReadAddress(startAddress + DisplaySize * (i + 1), DisplaySize);
}
foreach (var memoryModel in memoryModels)
{
listBox2.Items.Add(memoryModel.ByteStringAccordingToSize);
listBox3.Items.Add(memoryModel.CharRepresentation);
}
}

Related

Read characters from a single line including whitespaces rather than from a new line

IN C# i am trying to solve a problem :
Write a program that checks whether the product of the odd elements is equal to the product of the even elements.
The only thing left is:
On the second line you will receive N numbers separated by a whitespace.
I am unable to get this working. I have tried with Split but it keeps breaking. Can someone help?
Example:
Input
5
2 1 1 6 3
Output
yes 6
static void Main(string[] args)
{
long N = long.Parse(Console.ReadLine());
long[] array = new long[N];
long ODD = 1;
long EVEN = 1;
for (int i = 0; i < N; i++)
{
array[i] = int.Parse(Console.ReadLine());
if ((i + 1) % 2 == 0)
{
EVEN *= array[i];
}
else
{
ODD *= array[i];
}
}
if (EVEN == ODD)
{
Console.WriteLine("yes" + " " +
ODD);
}
else
{
Console.WriteLine("no" + " " + ODD + " " + EVEN);
}
}
Read from console input and keep it to an string array, Then convert each array element to long and apply the Odd Even logic like below:
static void Main(string[] args)
{
string input = Console.ReadLine();
string[] inputArray = input.Split(' ');
long element;
long odd = 1;
long even = 1;
foreach (var i in inputArray)
{
element = long.Parse(i);
if (element % 2 == 0)
{
even *= element;
}
else
{
odd *= element;
}
}
Console.WriteLine("\nOdd product = " + odd + ", Even product = " + even);
if (odd == even)
{
Console.WriteLine("ODD == EVEN \n");
Console.WriteLine("Yes" + " " + odd);
}
else
{
Console.WriteLine("ODD != EVEN \n");
Console.WriteLine("No" + " " + odd + " " + even);
}
Console.ReadKey();
}
long[] nums = input.Split(' ').Select(x => long.Parse(x))..ToArray(); //split numbers by space and cast them as int
int oddProduct = 1, evenProduct = 1; // initial values
foreach(long x in nums.Where(a => a%2 == 1))
oddProduct *= x; // multiply odd ones
foreach(long x in nums.Where(a => a%2 == 0))
evenProduct *= x; // multiply even ones

How convert a array object saved as string(base64?) to C# array or sql Table?

I have a legacy code that was developed in Ruby, it saves an Array as a string in the database that I would like to decode in the migration to the new environment.
Legacy Ruby Code:
class CatalogoConjunto
include DataMapper::Resource
...
property :coordenadas, Object
...
...
def save_depois
if (coordenadas.length > 1 and coordenadas.include?([0, 0]) rescue false)
self.coordenadas = coordenadas - [[0, 0]]
save!
end
end
def save
save = super
save_depois
save
end
...
end
Samples what saves in the column coordenadas:
"BAhbCFsHaQHYaQIDAVsHaQLZAWkCwwFbB2kB8WkCXQI= "
Other Samples:
"BAhbBlsHaQHRaQI6AQ== ", "BAhbBlsHaQLMAmkB3A== ", "BAhbB1sHaQKmAmkB81sHaQIkA2kBvQ== "
How do I find the encode method?
The new application uses C# and the data migration is being done in SQL ... but any light that shows me the way forward already helps me ...
Ruby makes me pretty lost.
Edit
The string "BAhbBlsHaQJ6A2kCIwI=" stand for this values (890, 547).
but using The following code i get the string "egMAACMCAAA="
Trying convert using C#
int[,] test = new int[,] { { 890, 547 } };
byte[] result = new byte[test.Length * sizeof(int)];
Buffer.BlockCopy(test, 0, result, 0, result.Length);
var anotherString = Convert.ToBase64String(result);
Console.WriteLine(anotherString);
var stringFromDatabase = "BAhbBlsHaQJ6A2kCIwI= ";
byte[] byteArray = Convert.FromBase64String(stringFromDatabase);
//Don't work
int[,] newArr = new int[byteArray.Length / sizeof(int)/2 + ((byteArray.Length / sizeof(int))%2), 2];
for (int ctr = 0; ctr < byteArray.Length / sizeof(int); ctr++)
{
if (ctr % 2 != 0)
{
newArr[ctr/2, 0] = BitConverter.ToInt32(byteArray, ctr * sizeof(int));
}
else
{
newArr[ctr/2, 1] = BitConverter.ToInt32(byteArray, ctr * sizeof(int));
}
}
The string generated by Ruby looks like Base64 but the values don't match
The DataMapper has a default bahavior to marshall the data type Object:
https://github.com/datamapper/dm-core/blob/master/lib/dm-core/property/object.rb
After some research found a post of how Marshall in Ruby work here:
https://ilyabylich.svbtle.com/ruby-marshalling-from-a-to-z
I just need the numbers them i did a simple decode just looking for the Integers
public static List<int> Conversor(string stringFromDatabase)
{
byte[] byteArray = Convert.FromBase64String(stringFromDatabase);
List<int> retorno = new List<int>();
for (int i = 0; i < byteArray.Length; i++)
{
if ((char)byteArray[i] == (char)105)
{
int valInt = 0;
int primeiroByte = Convert.ToInt32(byteArray[i + 1]);
if (primeiroByte == 0)
retorno.Add(0);
else if (primeiroByte > 4)
retorno.Add(primeiroByte - 5);
else if (primeiroByte > 0 && primeiroByte < 5)
{
valInt = byteArray[i + 2];
for (int y = 1; y < primeiroByte; y++)
{
valInt = valInt | (byteArray[i + 2 + y] << 8 * y);
}
retorno.Add(valInt);
}
}
}
return retorno;
}

Best way to do voice authentication in C#

I am building a voice authentication system and for that, I am using C# Speech recognition which lets me save the audio file which I convert and stores it as wav file.
I have another wav file in which I have stored my voice.
Then I am using FFT as mentioned here to compare 2 wav file and I use Cross Correlation code from here.
My openWav code is as below:
public static void openWav(string filename, out double[] left, out double[] right)
{
var numArray = File.ReadAllBytes(filename);
int num1 = numArray[22];
int index1;
int index2;
int num2;
for (index1 = 12;
numArray[index1] != 100 || numArray[index1 + 1] != 97 ||
(numArray[index1 + 2] != 116 || numArray[index1 + 3] != 97);
index1 = index2 + (4 + num2))
{
index2 = index1 + 4;
num2 = numArray[index2] + numArray[index2 + 1] * 256 + numArray[index2 + 2] * 65536 +
numArray[index2 + 3] * 16777216;
}
var index3 = index1 + 8;
var length = (numArray.Length - index3) / 2;
if (num1 == 2)
length /= 2;
left = new double[length];
right = num1 != 2 ? null : new double[length];
var index4 = 0;
while (index3 < numArray.Length)
{
left[index4] = bytesToDouble(numArray[index3], numArray[index3 + 1]);
index3 += 2;
if (num1 == 2)
{
right[index4] = bytesToDouble(numArray[index3], numArray[index3 + 1]);
index3 += 2;
}
++index4;
}
}
It works without error but every time I get the answer in between 0.6 to 0.8 even though it is not my voice.
Can anyone suggest where I am doing wrong or if there is any other way to do it in C#?

Points on chart graphic don't fit y-lines

Points on my second chart don't fit y-axis as you can see here:
Points values are exactly 50.0000, 49.9999, 49.9998 and 50.0001. But they are not on lines. And when I add point and with it increase number of values on y-axis, then points would fit y-axis, like in this picture.
Here is my code (sorry for Serbian text values)
TacnostVage tacnost = bazaPodataka.UcitajTacnostVage(Convert.ToString(dataGridView2.SelectedRows[0].Cells[2].Value), Convert.ToInt32(comboBox18.Text));
List<TestTacnostVage> testoviTacnost = bazaPodataka.UcitajTestoveTacnostVage(Convert.ToString(dataGridView2.SelectedRows[0].Cells[2].Value), Convert.ToInt32(comboBox18.Text));
chart2.ChartAreas.Clear();
chart2.Series.Clear();
prikažiToolStripMenuItem.DropDownItems.Clear();
tabeluToolStripMenuItem.DropDownItems.Clear();
string format = Convert.ToString(vaga.Podeljak);
format = format.Remove(format.Length - 1, 1) + "0";
if (testoviTacnost.Count != 0)
{
for (int i = 0; i < tacnost.NominalneMase.Count(); i++)
{
ChartArea area = new ChartArea();
Series series = new Series();
area.AxisY.MajorGrid.LineColor = Color.LightGray;
area.AxisX.MajorGrid.LineColor = Color.LightGray;
area.AxisY.LabelStyle.Format = format;
area.BorderColor = Color.LightGray;
area.BorderDashStyle = ChartDashStyle.Solid;
area.AxisY.Interval = vaga.Podeljak;
area.Name = "ChartArea" + (i + 1);
series.ChartType = SeriesChartType.Point;
series.ChartArea = "ChartArea" + (i + 1);
series.Name = "Tačka" + (i + 1);
string text = "";
TegoviTacnostVaga tegoviTacnost = bazaPodataka.UcitajTegoveTacnostVage(Convert.ToString(dataGridView2.SelectedRows[0].Cells[2].Value), Convert.ToInt32(comboBox18.Text), i);
if (tegoviTacnost != null)
{
for (int j = 0; j < tegoviTacnost.Proizvodjac.Count(); j++)
{
text += tegoviTacnost.Proizvodjac[j] + " ";
text += tegoviTacnost.SerijskiBrojevi[j] + " ";
text += tegoviTacnost.NominalneMase[j] + "g";
text += (j == tegoviTacnost.Proizvodjac.Count() - 1 ? "" : "\n");
}
}
series.LegendText = (text == "" ? "Nema podataka" : text);
for (int j = 0; j < testoviTacnost.Count(); j++)
series.Points.AddXY(testoviTacnost[j].RedniBrojTesta, testoviTacnost[j].RezultatiMerenja[i]);
area.AxisY.StripLines.Add(new StripLine() { BorderColor = Color.Red, IntervalOffset = (tacnost.RezultatiMerenja[i].Average() + koeficijentTacnost * ponovljivost.ReferentnaVrednost), Text = "Gornja granica: " + Convert.ToDouble(tacnost.RezultatiMerenja[i].Average() + koeficijentTacnost * ponovljivost.ReferentnaVrednost).ToString(format) });
area.AxisY.StripLines.Add(new StripLine() { BorderColor = Color.Red, IntervalOffset = (tacnost.RezultatiMerenja[i].Average() - koeficijentTacnost * ponovljivost.ReferentnaVrednost), Text = "Donja granica: " + Convert.ToDouble(tacnost.RezultatiMerenja[i].Average() - koeficijentTacnost * ponovljivost.ReferentnaVrednost).ToString(format) });
area.AxisY.Maximum = area.AxisY.StripLines[0].IntervalOffset + area.AxisY.Interval;
if (series.Points.FindMaxByValue().YValues[0] >= area.AxisY.Maximum)
area.AxisY.Maximum = series.Points.FindMaxByValue().YValues[0] + area.AxisY.Interval;
area.AxisY.Minimum = area.AxisY.StripLines[1].IntervalOffset - area.AxisY.Interval;
if (series.Points.FindMinByValue().YValues[0] <= area.AxisY.Minimum)
area.AxisY.Minimum = series.Points.FindMinByValue().YValues[0] - area.AxisY.Interval;
chart2.ChartAreas.Add(area);
chart2.Series.Add(series);
}
}
I found solution, but I'm not sure if this explanation is true. The problem was Axis-Y maximum. Charts Axis-Y interval was 0.0001 (4 decimals), but in my code, I put maximum to be StripLines IntervalOffset (which was more than 4 decimals) plus Charts Interval (in result that is more than 4 decimals). So probably this happens when your Chars Axis-Y Maximum and your Interval (if you set Interval) have different number of decimals. So I just simply rounded Strip Lines InvervalOffset to 4 decimals (in this case), and put Axis-Y Maximum to have 4 decimals like Interval has.

Filling a character array or a string - looking for a better way [duplicate]

This question already has an answer here:
copy a character with specific length
(1 answer)
Closed 7 years ago.
I have a written a very simple C# code that performs the following task:
given a number n which represents amount of spaces, my program will print the hourglass:
*****
***
*
***
*****
Beginning n spaces from the left boundary wall of the command window.
My code works as intended, but it is very very messy, disorganized, and I am sure there is a better way, perhaps something that was previously implemented in C# by microsoft developers who developed the .NET Framework.
This is my code:
public static void printAsterisk(int initialSpace)
{
int i, j;
char[] asteriskMsg = new char[5 * initialSpace + 25];
for (i = 0; i < initialSpace; i++)
{
asteriskMsg[i] = ' ';
}
for (j = i; j < i + 5; j++)
{
asteriskMsg[j] = '*';
}
asteriskMsg[j] = '\n';
for (i = j + 1; i < j + initialSpace + 1; i++)
{
asteriskMsg[i] = ' ';
}
for (j = i + 1; j < i + 4; j++)
{
asteriskMsg[j] = '*';
}
asteriskMsg[j] = '\n';
for (i = j + 1; i < j + initialSpace + 3; i++)
{
asteriskMsg[i] = ' ';
}
asteriskMsg[i] = '*';
asteriskMsg[i + 1] = '\n';
for (j = i + 2; j < i + initialSpace + 3; j++)
{
asteriskMsg[j] = ' ';
}
for (i = j; i < j + 3; i++)
{
asteriskMsg[i] = '*';
}
asteriskMsg[i] = '\n';
for (j = i + 1; j < i + initialSpace + 1; j++)
{
asteriskMsg[j] = ' ';
}
for (i = j; i < j + 5; i++)
{
asteriskMsg[i] = '*';
}
string s = new string(asteriskMsg);
System.Console.Write("{0}", s);
}
}
It is quite horrifying. I am very curious as to how to improve this code.
Just to show an example of what I mean, this is how the program runs with n=25
If n was zero, then you would have seen the same picture but starting from the left wall, rather than with 25 spaces. I hope it is clear now what I am trying to do.
Edit: Managed to come up with a great solution myself using strings!
public static void printAsterisk(int initialSpace)
{
string firstRow = "*****", secondRow = "***", thirdRow = "*", firstRowSpaces = new string(' ', initialSpace), secondRowSpaces = new string(' ', initialSpace+1), thirdRowSpaces = new string(' ', initialSpace+2);
string hourglass = string.Format("{0}{1}\n{2}{3}\n{4}{5}\n{2}{3}\n{0}{1}", firstRowSpaces, firstRow, secondRowSpaces, secondRow, thirdRowSpaces, thirdRow);
System.Console.WriteLine(hourglass);
}
I liked this question :)
This is my way of doing it. Really expecting others, since this is really fun :)
public class Program
{
public static void Main(string[] args)
{
PrintHourGlass(25);
}
/// <summary>
/// Prints an hour glass starting at the given offset
/// </summary>
/// <param name="indent">The starting offset</param>
static void PrintHourGlass(int indent)
{
PrintAsteriks(indent, 5); // offset = indent, print 5 * [I]*****
PrintAsteriks(indent + 1, 3); // offset = indent + 1, print 3 * [I] ***
PrintAsteriks(indent + 2, 1); // offset = indent +3, print 1 * [I] *
PrintAsteriks(indent + 1, 3); // offset = indent + 1, print 3 * [I] ***
PrintAsteriks(indent, 5); // offset = indent, print 5 * [I]*****
}
/// <summary>
/// Prints given number of * characters starting from the given offset
/// </summary>
/// <param name="indent">The starting offset</param>
/// <param name="asterisks">The number of * characters to print</param>
static void PrintAsteriks(int indent, int asterisks)
{
// Check starters guide to string.Format here:
// https://msdn.microsoft.com/en-us/library/system.string.format(v=vs.110).aspx#Starting
// string format uses a template and allows you to pass in and format arguments as you like.
// The template below evaluates to {0,25}{1} for indent = 25 and asteriks = 5
// which means,
// print argument 0 (first parameter), no extra formatting, pad the output to 25 characters
// print argument 1, no formatting
string formatString = "{0," + indent + "}{1}";
// Console.WriteLine method uses string.Format internally
// Below, for the template, argument 0 is null
// (since we want to print only 25 characters, the padding.
// The value could have been "" instead of null)
// Argument 1 is a string of * characters, with the length specified by asteriks parameter
Console.WriteLine(formatString, null, new string('*', asterisks));
// Therefore, it outputs 25 linear white spaces, then 5 * characters.
}
}

Categories

Resources