I am creating an application that will do the formula shown in this video - The Everything Formula
I suggest you watch it to understand this. I am trying to replicate the part of the video where he takes the graph and gets what 'k', (The y Coordinate), would be. I took every pixel of the image, and put it into a string containing the binary version. The binary number's length is so large, I cannot store it as an int or long.
Now, here is the part I cannot solve.
How would I convert a string containing a binary number into a base 10 number also in string format?
I Cannot use a long or int type, they are not large enough. Any conversion using the int type will also not work.
Example code:
public void GraphUpdate()
{
string binaryVersion = string.Empty;
for (int i = 0; i < 106; i++)
{
for (int m = 0; m < 17; m++)
{
PixelState p = Map[i, m]; // Map is a 2D array of PixelState, representing the grid / graph.
if (p == PixelState.Filled)
{
binaryVersion += "1";
}
else
{
binaryVersion += "0";
}
}
}
// Convert binaryVersion to base 10 without using int or long
}
public enum PixelState
{
Zero,
Filled
}
You can use BigInteger class, which is part of .NET 4.0.
See MSDN BigInteger Constructor, which takes as input byte[].
This byte[] is your binary number.
Result string can be retrieved by calling BigInteger.ToString()
Try using Int64. That works up to 9,223,372,036,854,775,807:
using System;
namespace StackOverflow_LargeBinStrToDeciStr
{
class Program
{
static void Main(string[] args)
{
Int64 n = Int64.MaxValue;
Console.WriteLine($"n = {n}"); // 9223372036854775807
string binStr = Convert.ToString(n, 2);
Console.WriteLine($"n as binary string = {binStr}"); // 111111111111111111111111111111111111111111111111111111111111111
Int64 x = Convert.ToInt64(binStr, 2);
Console.WriteLine($"x = {x}"); // 9223372036854775807
Console.ReadKey();
}
}
}
Related
I am trying to create a helper function that prepends x amounts of zeroes to the integer where x is the difference between a given length and the number of characters in that int.
For example:
// data = 9573132375
// length = 15
// should return (15 - 10) 000009573132375
public string ModulateData(long data, int length)
{
if (data.ToString().Length <= length)
{
int noToPrepend = length - data.ToString().Length;
string leadingzeros = "";
for (int i = 0; i < noToPrepend; i++)
{
leadingzeros += "0";
}
return leadingzeros + data.ToString();
}
return "";
}
I can only think of converting the data variable to a string, prepending 0s, and converting the string back to an integer later. However, I am concerned about the performance of this approach, as this method will be part of my core design, it needs to be as performant as possible. Is there a faster way this can be done? Are there any performance penalties with my current code?
EDIT
I am communicating the data variable as request data to a machine that accepts bytes, so I will be using this function as follows -
string requestdata = "";
requestdata += ModulateData(x,20);
requestdata += ModulateData(y,5);
requestdata += ModulateData(z,10); // Could be about 20 or so lines like this.
After that I will convert requestdata to a byte array in Hex Format. I already have working code for that.
Shorter version:
public static string ModulateData(long data, int length) =>
(data.ToString().Length <= length)
? $"{new string('0', length - data.ToString().Length)}{data}"
: string.Empty;
And more debuggable version, if you want:
public static string ModulateData(long data, int length)
{
var dataAsText = data.ToString();
if (dataAsText.Length <= length)
{
int noToPrepend = length - dataAsText.Length;
var leadingZeros = new string('0', noToPrepend);
return $"{leadingZeros}{dataAsText}";
}
return string.Empty;
}
And a usage:
// to make this more optimal you can calculate the StringBuilder initial capacity here,
// by taking into account possible characters length output
var requestData = new StringBuilder();
requestData.Append(ModulateData(x, 20));
requestData.Append(ModulateData(y, 5));
requestData.Append(ModulateData(z, 10));
My assignment is to search through the binary representation of a number and replace a matched pattern of another binary representation of a number. If I get a match, I convert the matching bits from the first integer into zeroes and move on.
For example the number 469 would be 111010101 and I have to match it with 5 (101). Here's the program I've written so far. Doesn't work as expected.
using System;
namespace Conductors
{
class Program
{
static void Main(string[] args)
{
//this is the number I'm searching for a match in
int binaryTicket = 469;
//This is the pattern I'm trying to match (101)
int binaryPerforator = 5;
string binaryTicket01 = Convert.ToString(binaryTicket, 2);
bool match = true;
//in a 32 bit integer, position 29 is the last one I would
//search in, since I'm searching for the next 3
for (int pos = 0; pos < 29; pos++)
{
for (int j = 0; j <= 3; j++)
{
var posInBinaryTicket = pos + j;
var posInPerforator = j;
int bitInBinaryTicket = (binaryTicket & (1 << posInBinaryTicket)) >> posInBinaryTicket;
int bitInPerforator = (binaryPerforator & (1 << posInPerforator)) >> posInPerforator;
if (bitInBinaryTicket != bitInPerforator)
{
match = false;
break;
}
else
{
//what would be the proper bitwise operator here?
bitInBinaryTicket = 0;
}
}
Console.WriteLine(binaryTicket01);
}
}
}
}
Few things:
Use uint for this. Makes things a hell of a lot easier when dealing with binary numbers.
You aren't really setting anything - you're simply storing information, which is why you're printing out the same number so often.
You should loop the x times where x = length of the binary string (not just 29). There's no need for inner loops
static void Main(string[] args)
{
//this is the number I'm searching for a match in
uint binaryTicket = 469;
//This is the pattern I'm trying to match (101)
uint binaryPerforator = 5;
var numBinaryDigits = Math.Ceiling(Math.Log(binaryTicket, 2));
for (var i = 0; i < numBinaryDigits; i++)
{
var perforatorShifted = binaryPerforator << i;
//We need to mask off the result (otherwise we fail for checking 101 -> 111)
//The mask will put 1s in each place the perforator is checking.
var perforDigits = (int)Math.Ceiling(Math.Log(perforatorShifted, 2));
uint mask = (uint)Math.Pow(2, perforDigits) - 1;
Console.WriteLine("Ticket:\t" + GetBinary(binaryTicket));
Console.WriteLine("Perfor:\t" + GetBinary(perforatorShifted));
Console.WriteLine("Mask :\t" + GetBinary(mask));
if ((binaryTicket & mask) == perforatorShifted)
{
Console.WriteLine("Match.");
//Imagine we have the case:
//Ticket:
//111010101
//Perforator:
//000000101
//Is a match. What binary operation can we do to 0-out the final 101?
//We need to AND it with
//111111010
//To get that value, we need to invert the perforatorShifted
//000000101
//XOR
//111111111
//EQUALS
//111111010
//Which would yield:
//111010101
//AND
//111110000
//Equals
//111010000
var flipped = perforatorShifted ^ ((uint)0xFFFFFFFF);
binaryTicket = binaryTicket & flipped;
}
}
string binaryTicket01 = Convert.ToString(binaryTicket, 2);
Console.WriteLine(binaryTicket01);
}
static string GetBinary(uint v)
{
return Convert.ToString(v, 2).PadLeft(32, '0');
}
Please read over the above code - if there's anything you don't understand, leave me a comment and I can run through it with you.
I am trying to develop a console application in C# which uses a WAV-file for input. The application should do a couple of things all in order, as shown below. First of all, the complete code:
class Program
{
static List<double> points = new List<double>();
static double maxValue = 0;
static double minValue = 1;
static int num = 0;
static int num2 = 0;
static List<double> values = new List<double>();
private static object akima;
static void Main(string[] args)
{
string[] fileLines = File.ReadAllLines(args[0]);
int count = 0;
foreach (string fileLine in fileLines)
{
if (!fileLine.Contains(";"))
{
string processLine = fileLine.Trim();
processLine = Regex.Replace(processLine, #"\s+", " ");
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
processLine = processLine.Replace(".", ",");
}
string[] dataParts = processLine.Split(Char.Parse(" "));
points.Add(double.Parse(dataParts[0]));
double value = Math.Pow(double.Parse(dataParts[1]), 2);
if (value > maxValue)
{
maxValue = value;
num = count;
}
values.Add(value);
}
count++;
}
for (int i = num; i < values.Count; i++)
{
if (values[i] < minValue)
{
minValue = values[i];
num2 = i;
}
}
Console.WriteLine(num + " " + num2);
int between = num2 - num;
points = points.GetRange(num, between);
values = values.GetRange(num, between);
List<double> defVal = new List<double>();
List<double> defValPoints = new List<double>();
alglib.spline1dinterpolant c;
alglib.spline1dbuildakima(points.ToArray(), values.ToArray(), out c);
double baseInt = alglib.spline1dintegrate(c, points[points.Count - 1]);
List<double> defETC = new List<double>();
for (int i = 0; i < points.Count; i += 10)
{
double toVal = points[i];
defETC.Add(10 * Math.Log10(values[i]));
defVal.Add(10 * Math.Log10((baseInt - alglib.spline1dintegrate(c, toVal)) / baseInt));
defValPoints.Add(points[i]);
}
WriteDoubleArrayToFile(defValPoints.ToArray(), defVal.ToArray(), "test.dat");
WriteDoubleArrayToFile(defValPoints.ToArray(), defETC.ToArray(), "etc.dat");
int end = 0;
for (int i = 0; i < points.Count; i++)
{
if (defVal[i] < -10)
{
end = i;
break;
}
}
//Console.WriteLine(num + " " + end);
int beginEDT = num;
int endEDT = num + end;
double timeBetween = (defValPoints[endEDT] - defValPoints[beginEDT]) * 6;
Console.WriteLine(timeBetween);
for (int i = 0; i < points.Count; i++)
{
}
Console.ReadLine();
}
static void WriteDoubleArrayToFile(double[] points, double[] values, string filename)
{
string[] defStr = new string[values.Length];
for (int i = 0; i < values.Length; i++)
{
defStr[i] = String.Format("{0,10}{1,25}", points[i], values[i]);
}
File.WriteAllLines(filename, defStr);
}
}
Extract the decimal/float/double value from the WAV-file
Create an array from extracted data
Create an Energy Time Curve that displays the decay of the noise/sound in a decibel-like way
Create an Decay Curve from the ETC created in step 3
Calculate things as Early Decay Time (EDT), T15/T20 and RT60 from this Decay Curve.
Display these Reverb Times in stdout.
At the moment I am sort of like half way through the process. I´ll explain what I did:
I used Sox to convert the audio file into a .dat file with numbers
I create an array using C# by simply splitting each line in the file above and putting the times in a TimesArray and the values at those points in a ValuesArray.
I am displaying a graph via GNUPlot, using the data processed with this function: 10 * Math.Log10(values[i]); (where i is an iterative integer in a for-loop iterating over all the items in the ValuesArray)
This is where I'm starting to get stuck. I mean, in this step I am using an Akima Spline function from Alglib to be able to integrate a line. I am doing that with a Schroeder integration (reversed), via this mathematical calculation: 10 * Math.Log10((baseInt - alglib.spline1dintegrate(c, toVal)) / baseInt); (where baseInt is a value calculated as a base integral for the complete curve, so I have a calculated bottom part of the reversed Schroeder integration. The c is a spline1dinterpolant made available when using the function alglib.spline1dbuildakima, which takes the timeArray as x values, valueArray as the y values, and c as an outwards spline1dinterpolant. toval is an x-value from the points array. The specific value is selected using a for-loop.) From these newly saved values I want to create an interpolated line and calculate the RT60 from that line, but I do not know how to do that.
Tried, did not really work out.
Same as above, I have no real values to show.
I'm quite stuck now, as I'm not sure if this is the right way to do it. If anyone can tell me how I can calculate the reverberation times in a fast and responsive way in C#, I'd be pleased to hear. The way of doing it might be completely different from what I have now, that's OK, just let me know!
Maybe you need to approach this differently:
start with the underlying maths. find out the mathematical formulas for these functions.
Use a simple mathematical function and calculate by hand (in excel or matlab) what the values should be (of all these things ETC, DC, EDC, T15, T20, RT60)
(A function such as a sine wave of just the minimum number of points you need )
then write a separate procedure to evaluate each of these in C# and verify your results for consistency with excel/matlab.
in C#, maybe store your data in a class that you pass around to each of the methods for its calculation.
your main function should end up something like this:
main(){
data = new Data();
//1, 2:
extract_data(data, filename);
//3:
energy_time_curve(data)
//...4, 5
//6:
display_results(data);
}
I am trying to generate nth bell number for large values between 500 to 1000.
Bells number is huge and i can't store it in ulong.
(To know bells number: http://en.wikipedia.org/wiki/Bell_number)
I tried the triangular method to compute the number.
Can any temme a way to save huge numbers like dat and perform the operation.
Here is the Code i wrote
using System;
class Program
{
static void Main(string[] args)
{
int length;
do
{
length =-1;
string numLength= Console.ReadLine();
if (int.TryParse(numLength, out length))
{
Console.WriteLine("Sequence length is : {0}",
TriangularMethod(length));
}
}while(length>0);
}
static ulong TriangularMethod(int n)
{
Dictionary<long, List<ulong>> triangle =
new Dictionary<long, List<ulong>>();
triangle.Add(1, new List<ulong>(new ulong[] { 1 }));
for (int i = 2; i <= n; i++)
{
triangle.Add(i, new List<ulong>());
triangle[i].Add(triangle[i - 1].Last());
ulong lastVal = 0;
for (int k = 1; k < i; k++)
{
lastVal = triangle[i][k - 1] + triangle[i - 1][k - 1];
triangle[i].Add(lastVal);
}
triangle.Remove(i - 2);
}
return triangle[n].Last();
}
}
If there is a faster way to compute the same. please temme.
use BigInteger Structure available in namespace System.Numerics
I think this would be useful to you
http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx
working with incredibly large numbers in .NET
http://www.codeproject.com/Articles/2728/C-BigInteger-Class
I just had the task in school to write a big adder. Meaning a method that can put very large numbers together.
We had 10 minutes and I did complete it on time. The teacher approved it.
I am not too satisfied with the result though, and I thought I perhaps were taking the wrong approach.
Here is my version:
using System;
using System.Text;
namespace kæmpe_adder
{
static class Program
{
static void Main()
{
var x = "1111";
var y = "111111111";
Console.WriteLine(BigAdder(x, y));
Console.ReadLine();
}
public static StringBuilder BigAdder(string x, string y)
{
var a = new StringBuilder(x);
var b = new StringBuilder(y);
return BigAdder(a, b);
}
public static StringBuilder BigAdder(StringBuilder x, StringBuilder y)
{
int biggest;
int carry = 0;
int sum;
var stringSum = new StringBuilder();
if (x.Length > y.Length)
{
y.FillString(x.Length - y.Length);
biggest = x.Length;
}
else if (y.Length > x.Length)
{
x.FillString(y.Length - x.Length);
biggest = y.Length;
}
else
{
biggest = y.Length;
}
for (int i = biggest - 1; i >= 0; i--)
{
sum = Convert.ToInt32(x[i].ToString()) + Convert.ToInt32(y[i].ToString()) + carry;
carry = sum / 10;
stringSum.Insert(0, sum % 10);
}
if (carry != 0)
{
stringSum.Insert(0, carry);
}
return stringSum;
}
public static void FillString(this StringBuilder str, int max)
{
for (int i = 0; i < max; i++)
{
str.Insert(0, "0");
}
}
}
}
When I wrote it, I thought of how you do it with binaries.
Is there a shorter and/or perhaps simpler way to do this?
From the algebraic point of view your code looks correct. From the design point of view, you would definitely prefer to encapsulate each of these big numbers in a class, so that you don't have to reference the string/string builders all the time. I am also not a big fan of this FillString approach, it seems more reasonable to add the digits while both numbers have non-zero values, and then just add the carry to the bigger number until you are done.
Not sure what was the question about binaries? The normal length numbers (32bit and 64bit) are added by the CPU as a single operation.
There are a number of open source implementations you could look to for inspiration.
http://www.codeproject.com/KB/cs/biginteger.aspx
http://biginteger.codeplex.com/
In general, I would recommend using an array of byte or long for best performance, but the conversion from a string to the array would be non-trivial.
Store the numbers in reverse order; this makes finding equivalent places trivial.
This makes it easier to add differently sized strings numbers:
int place = 0;
int carry = 0;
while ( place < shorter.Length ) {
result.Append (AddDigits (longer[place], shorter[place], ref carry));
++place;
}
while ( place < longer.Length ) {
result.Append (AddDigits (longer[place], 0, ref carry));
++place;
}
if ( carry != 0 )
result.Append (carry.ToString ());