I'm trying to convert double to binary, but when I run my project, I get System.Char[] in my text box instead of binary values. How can I solve this problem?
int bitCount = sizeof(float) * 8;
char[] result = new char[bitCount];
int intValue = System.BitConverter.ToInt32(BitConverter.GetBytes(testvalue), 0);
for (int bit = 0; bit < bitCount; ++bit)
{
int maskedValue = intValue & (1 << bit);
if (maskedValue > 0)
maskedValue = 1;
result[bitCount - bit - 1] = maskedValue.ToString()[0];
}
new string(result);
richTextBox1.Text = richTextBox1.Text+"\n"+result;
// pictureBox2.Image = bmp;
new string(result);
This is the problem. You do not assign this to any variable. I believe you should use it instead of result when you assing to textbox.Text.
You get System.Char[] in your text box, because ToString() for char arrays returns such a string.
So try following:
String resultString = new string(result);
richTextBox1.Text = richTextBox1.Text + Environment.NewLine + resultString;
Related
I am converting a floating point value to binary string representation:
float resulta = 31.0 / 15.0; //2.0666666
var rawbitsa = ToBinaryString(resulta); //returns 01000000000001000100010001000100
where ToBinaryString is coded as:
static string ToBinaryString(float value)
{
int bitCount = sizeof(float) * 8; // never rely on your knowledge of the size
// better not use string, to avoid ineffective string concatenation repeated in a loop
char[] result = new char[bitCount];
// now, most important thing: (int)value would be "semantic" cast of the same
// mathematical value (with possible rounding), something we don't want; so:
int intValue = System.BitConverter.ToInt32(BitConverter.GetBytes(value), 0);
for (int bit = 0; bit < bitCount; ++bit)
{
int maskedValue = intValue & (1 << bit); // this is how shift and mask is done.
if (maskedValue > 0)
maskedValue = 1;
// at this point, masked value is either int 0 or 1
result[bitCount - bit - 1] = maskedValue.ToString()[0];
}
return new string(result); // string from character array
}
Now I want to convert this binary string to float value.
I tried the following but it returns value "2.8293250329111622E-315"
string bstra = "01000000000001000100010001000100";
long w = 0;
for (int i = bstra.Length - 1; i >= 0; i--) w = (w << 1) + (bstra[i] - '0');
double da = BitConverter.ToDouble(BitConverter.GetBytes(w), 0); //returns 2.8293250329111622E-315
I want the value "2.0666666" by passing in value "01000000000001000100010001000100"
Why am I getting a wrong value? Am I missing something?
You're making this a lot harder than it needs to be; the error seems to be mostly in the character parsing code, but you don't need to do all that.
You could try like this instead:
static string ToBinaryString(float value)
{
const int bitCount = sizeof(float) * 8;
int intValue = System.BitConverter.ToInt32(BitConverter.GetBytes(value), 0);
return Convert.ToString(intValue, 2).PadLeft(bitCount, '0');
}
static float FromBinaryString(string bstra)
{
int intValue = Convert.ToInt32(bstra, 2);
return BitConverter.ToSingle(BitConverter.GetBytes(intValue), 0);
}
Example:
float resulta = 31.0F / 15.0F; //2.0666666
var rawbitsa = ToBinaryString(resulta);
Console.WriteLine(rawbitsa); //01000000000001000100010001000100
var back = FromBinaryString(rawbitsa);
Console.WriteLine(back); //2.0666666
Note that the usage of GetBytes is kinda inefficient; if you're OK with unsafe code, you can remove all of that.
Also note that this code is CPU-specific - it depends on the endianness.
I have strings that look like "01", "02". Is there an easy way that I can change the string into a number, add 1 and then change it back to a string so that these strings now look like "02", "03" etc. I'm not really good at C# as I just started and I have not had to get values before.
To get from a string to an integer, you can youse int.Parse():
int i = int.Parse("07");
To get back into a string with a specific format you can use string.Format():
strings = string.Format("{0:00}",7);
The latter should give "07" if I understand http://www.csharp-examples.net/string-format-int/ correctly.
You can convert the string into a number using Convert.ToInt32(), add 1, and use ToString() to convert it back.
int number = Convert.ToInt32(originalString);
number += 1;
string newString = number.ToString();
Parse the integer
int i = int.Parse("07");
add to your integer
i = i + 1;
make a new string variable and assign it to the string value of that integer
string newstring = i.ToString();
AddStringAndInt(string strNumber, int intNumber)
{
//TODO: Add error handling here
return string.Format("{0:00}", (int.TryParse(strNumber) + intNumber));
}
static string StringsADD(string s1, string s2)
{
int l1 = s1.Count();
int l2 = s2.Count();
int[] l3 = { l1, l2 };
int minlength = l3.Min();
int maxlength = l3.Max();
int komsu = 0;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < maxlength; i++)
{
Int32 e1 = Convert.ToInt32(s1.PadLeft(maxlength, '0').ElementAt(maxlength - 1 - i).ToString());
Int32 e2 = Convert.ToInt32(s2.PadLeft(maxlength, '0').ElementAt(maxlength - 1 - i).ToString());
Int32 sum = e1 + e2 + komsu;
if (sum >= 10)
{
sb.Append(sum - 10);
komsu = 1;
}
else
{
sb.Append(sum);
komsu = 0;
}
if (i == maxlength - 1 && komsu == 1)
{
sb.Append("1");
}
}
return new string(sb.ToString().Reverse().ToArray());
}
I needed to add huge numbers that are 1000 digit. The biggest number type in C# is double and it can only contain up to 39 digits. Here a code sample for adding very huge numbers treating them as strings.
I'm trying to convert a String of hex to ASCII, using this:
public void ConvertHex(String hexString)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hexString.Length; i += 2)
{
String hs = hexString.Substring(i, i + 2);
System.Convert.ToChar(System.Convert.ToUInt32(hexString.Substring(0, 2), 16)).ToString();
}
String ascii = sb.ToString();
MessageBox.Show(ascii);
}
but I get an out or bounds exception, I'm sure its a glaring error but other code I have tried does not work either. What am I doing wrong?
This code will convert the hex string into ASCII, you can copy paste this into a class and use it without instancing
public static string ConvertHex(String hexString)
{
try
{
string ascii = string.Empty;
for (int i = 0; i < hexString.Length; i += 2)
{
String hs = string.Empty;
hs = hexString.Substring(i,2);
uint decval = System.Convert.ToUInt32(hs, 16);
char character = System.Convert.ToChar(decval);
ascii += character;
}
return ascii;
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
return string.Empty;
}
Notes
2 = the no. of hexString chars used to represent an ASCII character.
System.Convert.ToUInt32(hs, 16) = "convert the base 16 hex substrings to an unsigned 32 bit int"
There are four three problems here:
Since you're incrementing i by 2 on each iteration, you need to terminate at hexString.Length - 1. This doesn't actually matter; incrementing by two after the final iteration will bring the counter above the checked length regardless.
You're taking the wrong number of characters from hexString.
hs is never used.
You're not appending anything to sb.
Try this:
for (int i = 0; i < hexString.Length; i += 2)
{
string hs = hexString.Substring(i, 2);
sb.Append(Convert.ToChar(Convert.ToUInt32(hs, 16)));
}
Note that there's no need to qualify the types with their namespace, System (assuming you've referenced it at the top of the file with a using statement).
String hs = hexString.Substring(i, i + 2);
System.Convert.ToChar(System.Convert.ToUInt32(hexString.Substring(0, 2), 16)).ToString();
Do you notice you're never using hs ??
And that you're converting the first 2 chars over and over?
Since you are incrementing your index by 2, you need to stop your loop one-before-the-end of the length of the string. Otherwise your last iteration of the loop will try to read characters past the end of the string.
for (int i = 0; i < hexString.Length - 1, i += 2)
I am trying to edit a line of a text file (.Hex file) containing all Hex characters without using pointers and in a more efficient way.
It takes so long because the program I have to edit some (around 30x4 bytes or 30 float values from the address values of hex file).
Every time the program replaces one byte, it searches the complete file and replaces the values, and copy back back again the new file to another file. This process repeats 30 times, which is quite time consuming and hence not looks appropriate.
What would be the most efficient method?
public static string putbyteinhexfile(int address, char data, string total)
{
int temph, temphl, tempht;
ushort checksum = 0;
string output = null, hexa = null;
StreamReader hex;
RegistryKey reg = Registry.CurrentUser;
reg = reg.OpenSubKey("Software\\Calibratortest");
hex = new StreamReader(((string)reg.GetValue("Select Input Hex File")));
StreamReader map = new StreamReader((string)reg.GetValue("Select Linker Map File"));
while ((output = hex.ReadLine()) != null)
{
checksum = 0;
temph = Convert.ToInt16(("0x" + output.Substring(3, 4)), 16);
temphl = Convert.ToInt16(("0x" + output.Substring(1, 2)), 16);
tempht = Convert.ToInt16(("0x" + output.Substring(7, 2)), 16);
if (address >= temph &&
address < temph + temphl &&
tempht == 0)
{
output = output.Remove((address - temph) * 2 + 9, 2);
output = output.Insert((address - temph) * 2 + 9,
String.Format("{0:X2}", Convert.ToInt16(data)));
for (int i = 1; i < (output.Length - 1) / 2; i++)
checksum += (ushort)Convert.ToUInt16(output.Substring((i * 2) - 1, 2), 16);
hexa = ((~checksum + 1).ToString("x8")).ToUpper();
output = output.Remove(temphl * 2 + 9, 2);
output = output.Insert(temphl * 2 + 9,
hexa.Substring(hexa.Length - 2, 2));
break;
}
else total = total + output + '\r' + '\n';
}
hex.Close();
map.Close();
return total;
}
Assuming you don't want to massively rewrite your existing logic which does 'for each line, do this search and replace logic', I'd think the simplest change would be:
var lines = File.ReadAllLines(filePath);
foreach (change to make)
{
for (int i = 0; i < lines.Length; i++)
{
// read values from line
if (need_to_modify)
{
// whatever change logic you want here.
lines[i] = lines[i].Replace(...);
}
}
}
File.WriteAllLines(filePath, lines);
Basically, you'll still do the logic you have now, except:
You read the file once instead of N times
you get rid of streamreader / streamwriter work
you do your changes on the array of strings in memory
string fileName = "blabla.hex";
StreamReader f1 = File.OpenText(fileName);
StreamWriter f2 = File.CreateText(fileName + ".temp_");
while (!f1.EndOfStream)
{
String s = f1.ReadLine();
//change the content of the variable 's' as you wish
f2.WriteLine(s);
}
f1.Close();
f2.Close();
File.Replace(fileName + ".temp_", fileName, null);
I have an image data type in my table. When I query using SQL Server Management Studio, I get the following in my results window, both grid and text.
0x255044462D312E320D0A0D0A332030206F[Truncated for Length]
I am attempting to replicate this in a little c# program.
However, when I use either SqlCommand or LINQ I get the output:
JVBERi0xLjINCg0KMyAwIG9iag0KPDwNCi9FIDIxODgyDQovSCBbIDExNTAgMTUxIF0NCi9MIDIyM[TRUNCATED]
Any thoughts to what I need to do to get the 0x25... output to display? I have tried doing byte[] conversions and Encoding, but can't seem to find the right one.
If I am not clear, please let me know.
Edit:
I am not trying to display the image, just the 0x25...
Thoughts?
string forDisplay = "0x" + BitConverter.ToString(yourByteArray).Replace("-", "");
AFAIK, .Net does not include any methods to print an arbitrary byte array as a single hex number. (Until .Net 4.0's System.Numerics.BigInteger)
However, you should be able to write
"0x" + BitConverter.ToString(bytes).Replace("-", "")
Note that this is incredibly inefficient; if you want to do this in real code, use a StringBuilder in a loop. EDIT: Like this:
public static string ToHexString(this byte[] bytes) {
var builder = new StringBuilder(bytes.Length * 2 + 2);
builder.Append("0x");
for (int i = 0; i < bytes.Length; i++)
builder.Append(bytes[i].ToString("X2"));
return builder.ToString();
}
2nd EDIT: Here's a new version which really is faster. (Yes, I know you don't need it; here it is anyway)
private static char ToHexDigit(int i) {
if (i < 10)
return (char)(i + '0');
return (char)(i - 10 + 'A');
}
public static string ToHexString(byte[] bytes) {
var chars = new char[bytes.Length * 2 + 2];
chars[0] = '0';
chars[1] = 'x';
for (int i = 0; i < bytes.Length; i++) {
chars[2 * i + 2] = ToHexDigit(bytes[i] / 16);
chars[2 * i + 3] = ToHexDigit(bytes[i] % 16);
}
return new string(chars);
}