C# converting int to hex [duplicate] - c#

This question already has answers here:
Convert integer to hexadecimal and back again
(11 answers)
Closed 8 years ago.
This is a small snippet of the code I have written in Visual Studio.
I need to convert the int add into an hex value (later into a string) as I am accessing the memory of a uC. But when I view the variable during debugging it displays it as a string "add16". What could I be doing wrong?
for (int add = 0; add <= 0xfffff; )
{
for (int X = 0; X <= 15; X++)
{
string address = add.ToString("add16");
addr = Convert.ToString(address);
port.WriteLine(String.Format("WRBK:{0}:{1}", addr, parts[X]));
add++;
}
}

There is a simple and very convenient method that takes an integer and returns a representation of it as a string in hexadecimal notation
string address = Convert.ToString(add, 16);
So, perhaps, your internal loop could be rewritten as
port.WriteLine(String.Format("WRBK:{0}:{1}", Convert.ToString(add++, 16), parts[X]));
and using the standard numeric format strings specifiers reduced to
port.WriteLine(String.Format("WRBK:{0:X}:{1}", add++, parts[X]));

You can tell .NET's String.Format to use hex output for the integer, eliminating any code to hex conversion, use:
port.WriteLine(String.Format("WRBK:{0:X}:{1}", add, parts[X]));

Related

Converting int to char in c#. But after converting the value, char holds nothing [duplicate]

This question already has answers here:
C#: Convert int to char, but in literal not unicode representation
(2 answers)
Closed 7 months ago.
char chr1 = '9';
int num = 9;
char chr2 = (char)num;
if(chr1 == chr2)
Console.WriteLine("It worked");
else
Console.WriteLine("It did not work");
Console.WriteLine(chr2.GetType().Name);
Console.Write(chr2);
I want to convert an int to a char and compare it with another char. When i ran this code the output is
It did not work
Char
So it converts int to a char successfully but chr2 has no value it prints nothing (but its move the cursor)
Hence it has no value if is not working but i didn't understand why chr2 has no value.
just use this
char chr2 = Convert.ToChar(num.ToString());
or thanks to #Charlieface
char chr2 = num.ToString()[0];
this is because
num=Convert.ToByte(9); //9 it is invisible ASCII code - horisontal tab
num=Convert.ToByte('9') //57 it is visible ASCII code '9'

Why can't I convert an integer into binary with Convert.ToInt32? [duplicate]

This question already has answers here:
Convert integer to binary in C#
(22 answers)
Closed 3 years ago.
By using that statement I can change my binary value to decimal value by swapping the values but why isn't this statement working for decimal to binary conversion?
int decimalVal = 10;
int binaryVal = Convert.ToInt32(decimalVal, 2); // want 1010
You should use Convert.ToInt32(String, Int32) method to convert binary to integer and Convert.ToString(Int32, Int32) method to convert integer to binary.
string binaryVal = Convert.ToString(decimalVal, 2);
To find more information:
https://learn.microsoft.com/en-us/dotnet/api/system.convert.toint32?view=netframework-4.8
https://learn.microsoft.com/en-us/dotnet/api/system.convert.tostring?view=netframework-4.8
int decimalVal = 10;
string binary = Convert.ToString(decimalVal, 2);
They are of different byte sizes: https://condor.depaul.edu/sjost/nwdp/notes/cs1/CSDatatypes.htm And you are trying to convert one directly and expect binary while this does not work like that.
This two answers should help you:
How do I convert a decimal to an int in C#?
And
Convert integer to binary in C#
What you will figure out from this two answers is that Covnert.ToInt32 does not have an overload that takes an instance of decimal and converts it to binary. You will need to cast the decimal first to an integer and then you would be able to cast it to binary, For example:
decimal value = 8;
int n = Convert.ToInt32(value);
string binary = Convert.ToString(n, 2);
binary.Dump();
The output would be: 1000
This example is tested in Linqpad

Convert to base 2 then split in an array [duplicate]

This question already has answers here:
Convert int to a bit array in .NET
(10 answers)
Closed 7 years ago.
I want to convert my base 10 number to base 2 and then store parts in an array.
Here are two examples:
my value is 5 so it will be converted to 101 then I have an array like this: {1,0,1}
or my value is 26 so it will be converted to 11010 then I will have an array like this: {0,1,0,1,1}
Thank you in advance for your time and consideration.
To convert the int 'x'
int x = 3;
One way, by manipulation on the int :
string s = Convert.ToString(x, 2); //Convert to binary in a string
int[] bits= s.PadLeft(8, '0') // Add 0's from left
.Select(c => int.Parse(c.ToString())) // convert each char to int
.ToArray(); // Convert IEnumerable from select to Array
Alternatively, by using the BitArray class-
BitArray b = new BitArray(new byte[] { x });
int[] bits = b.Cast<bool>().Select(bit => bit ? 1 : 0).ToArray();
Source: https://stackoverflow.com/a/6758288/1560697

How to write javascript equivalent of Convert.ToBase64String() in javascript? [duplicate]

This question already has answers here:
How can you encode a string to Base64 in JavaScript?
(33 answers)
Closed 9 years ago.
I have byte array and I can convert this usin Convert.ToBase64String() method in c#.
I wrote equivalent of this method in javascript like below. But the result is different.
in c#:
byte[] data = ...
Convert.ToBase64String(data)
in js
function GetStringFromByteArray(array) {
var result = "";
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < array[i].length; j++)
result += String.fromCharCode(array[i][j]);
}
return result;
}
How can I succeed this in js?
Yes, the result is different, because the Javascript function doesn't do base64 encoding at all.
The base64 encoded data contains six bits of information per character, so the eight bits of a character code is spread out over two characters in the encoded data.
To encode the data, you have to regroup the bits in the bytes into six bit groups, then you can convert each group into a base64 character.
See: Base64
You can use this javascript library

c# equivalent of fscanf() [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Looking for C# equivalent of scanf
I am trying to convert a line of code from c to c#
fscanf(fp, "%d %d\n", &x,&y);
is there an equivalent function for fscanf() in c#? how do i convert this line of code?
Update:
fp is a file pointer to a text file which contains an input like this
0 0
I need to save the integer inputs to x and y, respectively.
var parts = streamReader.ReadLine().Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries);
int x = Int32.Parse(parts[0]);
int y = Int32.Parse(parts[1]);
String.Format("someFormatString", MyFileStreamReader.ReadLine());
Check out the BinaryReader class. In C# you would use a Stream object in place of the C FILE pointer. Something like this should work
System.IO.Stream fp = System.IO.File.OpenRead(#"C:\Path\To\My\File.txt");
double x, y;
using (var reader = new System.IO.BinaryReader(fp))
{
x = reader.ReadDouble();
y = reader.ReadDouble();
}

Categories