Converting string or char to int - c#

I'm totally puzzled
string temp = "73";
int tempc0 = Convert.ToInt32(temp[0]);
int tempc1 = Convert.ToInt32(temp[1]);
MessageBox.Show(tempc0 + "*" + tempc1 + "=" + tempc0*tempc1);
I would expect: 7*3=21
But then I receive: 55*51=2805

That is the ASCII value for the character 7 and 3. If you want number representation then you can convert each character to string and then use Convert.ToString:
string temp = "73";
int tempc0 = Convert.ToInt32(temp[0].ToString());
int tempc1 = Convert.ToInt32(temp[1].ToString());
MessageBox.Show(tempc0 + "*" + tempc1 + "=" + tempc0*tempc1);

55 and 51 are their locations in the ascii chart.
Link to chart - http://kimsehoon.com/files/attach/images/149/759/007/ascii%281%29.png
try using int.parse

This works:
string temp = "73";
int tempc0 = Convert.ToInt32(temp[0].ToString());
int tempc1 = Convert.ToInt32(temp[1].ToString());
Console.WriteLine(tempc0 + "*" + tempc1 + "=" + tempc0 * tempc1);
You have to do ToString() to get the actual string representation.

You are getting the ASCII codes for 7 and 3, which are 55 and 51 respectively.
Use int.Parse() to convert a char or string to a value.
int tempc0 = int.Parse(temp[0].ToString());
int tempc1 = int.Parse(temp[1].ToString());
int product = tempc0 * tempc1; // 7 * 3 = 21
int.Parse() doesn't accept a char as a parameter, so you have to convert to string first, or use temp.SubString(0, 1) instead.

This works, and is more computationally efficient than using either int.Parse() or Convert.ToInt32():
string temp = "73";
int tempc0 = temp[0] - '0';
int tempc1 = temp[1] - '0';
MessageBox.Show(tempc0 + "*" + tempc1 + "=" + tempc0 * tempc1);

Converting a character to an integer gives you the Unicode character code. If you convert a string to integer it will be parsed as a number:
string temp = "73";
int tempc0 = Convert.ToInt32(temp.Substring(0, 1));
int tempc1 = Convert.ToInt32(temp.Substring(1, 1));

When you write string temp = "73", your temp[0] and temp[1] are being char values.
From Convert.ToInt32 Method(Char) method
Converts the value of the specified Unicode character to the
equivalent 32-bit signed integer.
That means converting a char to an int32 gives you the unicode character code.
You just need to use .ToString() method your your temp[0] and temp[1] values. Like;
string temp = "73";
int tempc0 = Convert.ToInt32(temp[0].ToString());
int tempc1 = Convert.ToInt32(temp[1].ToString());
MessageBox.Show(tempc0 + "*" + tempc1 + "=" + tempc0*tempc1);
Here is a DEMO.

Related

How to split string by number of characters and add at the begin of each string custom string

For example I have some string, length of this string = 2900
How can I divide this string by parts(length 255) and add for each part "Part {number}" + dividing string
On input: string (2900 length)
Output: List with 12 element and each element should be = Part {number} + substring and length less than 255
I try smth like that, but I have trouble when I have more than 9 part
public static IEnumerable<string> SplitJobComment(string str, int chunkLength)
{
var partNumber = 1;
var partNumberTemplate = $"Part {partNumber} ";
chunkLength -= partNumberTemplate.Length;
for (var i = 0; i < str.Length; i += chunkLength)
{
if (chunkLength + i > str.Length)
{
chunkLength = str.Length - i;
}
partNumberTemplate = $"Part {partNumber} ";
partNumber++;
yield return partNumberTemplate + str.Substring(i, chunkLength);
}
}
Given that the real problem, as I assumed, is the fact that partNumberTemplate's length changes when partNumber>9, one possibile solution can be
var partNumberTemplate = $"Part {partNumber:D2} ";
{partNumber:D2} formats the number using always 2 digits.

C# code to vba code for decryption

I need assistance or someone that can point me in the right direction
I have Acces Vba code that does a custom encryption and i need to rewrite this code for a c# application
I have already done all of the code conversions but the results are not the same
I think it could be the encoding standard but I'm not sure
Edit
I cant use any extra libraries it must all be native C#
(I know of the vb Library)
C#
internal class Class1
{
public string fEncryptString(string TheString, int nbrPlaces)
{
//string sEnc = "91tephen#S", expected = "œ˜:²84²7 ©";
int i, intlength;
double mult, tmp;
string tmpst = "";
intlength = TheString.Length;
nbrPlaces = (nbrPlaces % 8);
mult = Math.Pow(2, nbrPlaces);
for (i = 1; i < intlength + 1; i++)
{
tmp = Convert.ToChar(Mid(TheString, i, 1));
tmp = tmp * mult;
tmp = tmp % 256 + tmp / 256;
tmp = Math.Floor(tmp);
int x = Convert.ToInt16(tmp);
tmpst = tmpst + Encoding.Default.GetString(new byte[] { Convert.ToByte(x) });
}
return tmpst;
}
public string Mid(string s, int a, int b)
{
string temp = s.Substring(a - 1, b);
return temp;
}
public string Encrypt(string strString)
{
//Scramble the order of characters
int intLen;
string strRtt = "";
//Determine length of string
intLen = strString.Length;
//Assign first two characters
strRtt = strString.Substring(strString.Length - 1) + strString.Substring(strString.Length - 2, 1);
//Assign all other characters except the last character
for (int i = 2; i < intLen - 1; i++)
{
strRtt += Mid(strString, i, 1);
}
//Assign the last character
strRtt = strRtt + strString.Substring(1, 1);
//Encrypt the scrambled string
return fEncryptString(strRtt, 7);
}
}
VBA
Public Function fEncryptString(TheString As String, ByVal nbrPlaces As Byte) As String
Dim tmp As Integer, i As Integer, mult As Integer
Dim intLength As Integer, tmpSt As String
intLength = Len(TheString)
tmpSt = ""
nbrPlaces = nbrPlaces Mod 8 'no point doing more than 7, besides
mult = 2 ^ nbrPlaces 'mult (an Integer) would be too small
For i = 1 To intLength
tmp = Asc(Mid$(TheString, i, 1)) 'get the ASCII value of each character
tmp = tmp * mult 'apply the multiplier
tmp = tmp Mod 256 + tmp \ 256 'rotate any 'carry' bit
tmpSt = tmpSt & Chr$(tmp) 'add the character to the String
Next i
fEncryptString = tmpSt
End Function
Public Function fEncrypt(strString As String)
'Scramble the order of characters
Dim intLen As Integer
Dim strRtt As String
'Determine length of string
intLen = Len(strString)
'Assign first two characters
strRtt = Right(strString, 1) & Left(Right(strString, 2), 1)
'Assign all other characters except the last character
For i = 2 To intLen - 2
strRtt = strRtt & Mid(strString, i, 1)
Next i
'Assign the last character
strRtt = strRtt & Left(strString, 1)
'Encrypt the scrambled string
fEncrypt = fEncryptString(strRtt, 7)
End Function

Concatenate binaries then convert to int

string middlePart = "1111";
string leftPart = "0000";
string rightPart = "0000";
I want to concatenate all three of these together to make 000011110000, and convert that binary to a int.
The code below will not work because the number is way too big.
int maskingVal = Convert.ToByte((leftPart+middlePart+rightPart), 2);
Is there any way to do the Convert.ToByte on each individual part of the binary to int, and concatenate their binary equivalent to get the correct int value of 000011110000.
Thank you
I don't know why do you simply not do
var maskingVal = Convert.ToInt16((leftPart + middlePart + rightPart), 2);
but you can do it this way too
byte middlePart = Convert.ToByte("1111", 2);
byte leftPart = Convert.ToByte("0000",2);
byte rightPart = Convert.ToByte("0000",2);
var maskingVal = leftPart << 8 | middlePart << 4 | rightPart;
As indicated by Adriano Repetti, you can specify base 2:
int maskingVal = Convert.ToInt32(leftPart+middlePart+rightPart, 2);
string middlePart = "1111";
string leftPart = "0000";
string rightPart = "0000";
int leftVal = Convert.ToByte(leftPart, 2) * 256;
int middleVal = Convert.ToByte(middlePart, 2) * 16;
int rightVal = Convert.ToByte(rightPart, 2);
int maskingVal = leftVal + middleVal + rightVal;
You could just skip converting and calculate the value yourself.
string middlePart = "1111";
string leftPart = "0000";
string rightPart = "0000";
string combine = leftPart + middlePart + rightPart;
long value = 0;
for (int i = combine.Length - 1, exponent = 1; i >= 0; i--, exponent *= 2)
{
if (combine[i] == '1')
{
value += exponent;
}
}
Console.WriteLine(value);
Result:
240

Convert an integer to a binary string with leading zeros

I need to convert int to bin and with extra bits.
string aaa = Convert.ToString(3, 2);
it returns 11, but I need 0011, or 00000011.
How is it done?
11 is binary representation of 3. The binary representation of this value is 2 bits.
3 = 20 * 1 + 21 * 1
You can use String.PadLeft(Int, Char) method to add these zeros.
// convert number 3 to binary string.
// And pad '0' to the left until string will be not less then 4 characters
Convert.ToString(3, 2).PadLeft(4, '0') // 0011
Convert.ToString(3, 2).PadLeft(8, '0') // 00000011
I've created a method to dynamically write leading zeroes
public static string ToBinary(int myValue)
{
string binVal = Convert.ToString(myValue, 2);
int bits = 0;
int bitblock = 4;
for (int i = 0; i < binVal.Length; i = i + bitblock)
{ bits += bitblock; }
return binVal.PadLeft(bits, '0');
}
At first we convert my value to binary.
Initializing the bits to set the length for binary output.
One Bitblock has 4 Digits. In for-loop we check the length of our converted binary value und adds the "bits" for the length for binary output.
Examples:
Input: 1 -> 0001;
Input: 127 -> 01111111
etc....
You can use these methods:
public static class BinaryExt
{
public static string ToBinary(this int number, int bitsLength = 32)
{
return NumberToBinary(number, bitsLength);
}
public static string NumberToBinary(int number, int bitsLength = 32)
{
string result = Convert.ToString(number, 2).PadLeft(bitsLength, '0');
return result;
}
public static int FromBinaryToInt(this string binary)
{
return BinaryToInt(binary);
}
public static int BinaryToInt(string binary)
{
return Convert.ToInt32(binary, 2);
}
}
Sample:
int number = 3;
string byte3 = number.ToBinary(8); // output: 00000011
string bits32 = BinaryExt.NumberToBinary(3); // output: 00000000000000000000000000000011
public static String HexToBinString(this String value)
{
String binaryString = Convert.ToString(Convert.ToInt32(value, 16), 2);
Int32 zeroCount = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(binaryString.Length) / 8)) * 8;
return binaryString.PadLeft(zeroCount, '0');
}
Just what Soner answered use:
Convert.ToString(3, 2).PadLeft(4, '0')
Just want to add just for you to know. The int parameter is the total number of characters that your string and the char parameter is the character that will be added to fill the lacking space in your string. In your example, you want the output 0011 which which is 4 characters and needs 0's thus you use 4 as int param and '0' in char.
string aaa = Convert.ToString(3, 2).PadLeft(10, '0');
This may not be the most elegant solution but it is the fastest from my testing:
string IntToBinary(int value, int totalDigits) {
char[] output = new char[totalDigits];
int diff = sizeof(int) * 8 - totalDigits;
for (int n = 0; n != totalDigits; ++n) {
output[n] = (char)('0' + (char)((((uint)value << (n + diff))) >> (sizeof(int) * 8 - 1)));
}
return new string(output);
}
string LongToBinary(int value, int totalDigits) {
char[] output = new char[totalDigits];
int diff = sizeof(long) * 8 - totalDigits;
for (int n = 0; n != totalDigits; ++n) {
output[n] = (char)('0' + (char)((((ulong)value << (n + diff))) >> (sizeof(long) * 8 - 1)));
}
return new string(output);
}
This version completely avoids if statements and therfore branching which creates very fast and most importantly linear code. This beats the Convert.ToString() function from microsoft by up to 50%
Here is some benchmark code
long testConv(Func<int, int, string> fun, int value, int digits, long avg) {
long result = 0;
for (long n = 0; n < avg; n++) {
var sw = Stopwatch.StartNew();
fun(value, digits);
result += sw.ElapsedTicks;
}
Console.WriteLine((string)fun(value, digits));
return result / (avg / 100);//for bigger output values
}
string IntToBinary(int value, int totalDigits) {
char[] output = new char[totalDigits];
int diff = sizeof(int) * 8 - totalDigits;
for (int n = 0; n != totalDigits; ++n) {
output[n] = (char)('0' + (char)((((uint)value << (n + diff))) >> (sizeof(int) * 8 - 1)));
}
return new string(output);
}
string Microsoft(int value, int totalDigits) {
return Convert.ToString(value, toBase: 2).PadLeft(totalDigits, '0');
}
int v = 123, it = 10000000;
Console.WriteLine(testConv(Microsoft, v, 10, it));
Console.WriteLine(testConv(IntToBinary, v, 10, it));
Here are my results
0001111011
122
0001111011
75
Microsofts Method takes 1.22 ticks while mine only takes 0.75 ticks
With this you can get binary representation of string with corresponding leading zeros.
string binaryString = Convert.ToString(3, 2);;
int myOffset = 4;
string modified = binaryString.PadLeft(binaryString.Length % myOffset == 0 ? binaryString.Length : binaryString.Length + (myOffset - binaryString.Length % myOffset), '0'));
In your case modified string will be 0011, if you want you can change offset to 8, for instance, and you will get 00000011 and so on.

How to get ASCII value of string in C#

I want to get the ASCII value of characters in a string in C#.
If my string has the value "9quali52ty3", I want an array with the ASCII values of each of the 11 characters.
How can I get ASCII values in C#?
From MSDN
string value = "9quali52ty3";
// Convert the string into a byte[].
byte[] asciiBytes = Encoding.ASCII.GetBytes(value);
You now have an array of the ASCII value of the bytes. I got the following:
57
113
117
97
108
105
53
50
116
121
51
string s = "9quali52ty3";
foreach(char c in s)
{
Console.WriteLine((int)c);
}
This should work:
string s = "9quali52ty3";
byte[] ASCIIValues = Encoding.ASCII.GetBytes(s);
foreach(byte b in ASCIIValues) {
Console.WriteLine(b);
}
Do you mean you only want the alphabetic characters and not the digits? So you want "quality" as a result? You can use Char.IsLetter or Char.IsDigit to filter them out one by one.
string s = "9quali52ty3";
StringBuilder result = new StringBuilder();
foreach(char c in s)
{
if (Char.IsLetter(c))
result.Add(c);
}
Console.WriteLine(result); // quality
string text = "ABCD";
for (int i = 0; i < text.Length; i++)
{
Console.WriteLine(text[i] + " => " + Char.ConvertToUtf32(text, i));
}
If I remember correctly, the ASCII value is the number of the lower seven bits of the Unicode number.
string value = "mahesh";
// Convert the string into a byte[].
byte[] asciiBytes = Encoding.ASCII.GetBytes(value);
for (int i = 0; i < value.Length; i++)
{
Console.WriteLine(value.Substring(i, 1) + " as ASCII value of: " + asciiBytes[i]);
}
This program will accept more than one character and output their ASCII value:
using System;
class ASCII
{
public static void Main(string [] args)
{
string s;
Console.WriteLine(" Enter your sentence: ");
s = Console.ReadLine();
foreach (char c in s)
{
Console.WriteLine((int)c);
}
}
}
Or in LINQ:
string value = "9quali52ty3";
var ascii_values = value.Select(x => (int)x);
var as_hex = value.Select(x => ((int)x).ToString("X02"));
If you want the charcode for each character in the string, you could do something like this:
char[] chars = "9quali52ty3".ToCharArray();
byte[] asciiBytes = Encoding.ASCII.GetBytes("Y");
foreach (byte b in asciiBytes)
{
MessageBox.Show("" + b);
}
Earlier responders have answered the question but have not provided the information the title led me to expect. I had a method that returned a one character string but
I wanted a character which I could convert to hexadecimal. The following code demonstrates what I thought I would find in the hope it is helpful to others.
string s = "\ta£\x0394\x221A"; // tab; lower case a; pound sign; Greek delta;
// square root
Debug.Print(s);
char c = s[0];
int i = (int)c;
string x = i.ToString("X");
c = s[1];
i = (int)c;
x = i.ToString("X");
Debug.Print(c.ToString() + " " + i.ToString() + " " + x);
c = s[2];
i = (int)c;
x = i.ToString("X");
Debug.Print(c.ToString() + " " + i.ToString() + " " + x);
c = s[3];
i = (int)c;
x = i.ToString("X");
Debug.Print(c.ToString() + " " + i.ToString() + " " + x);
c = s[4];
i = (int)c;
x = i.ToString("X");
Debug.Print(c.ToString() + " " + i.ToString() + " " + x);
The above code outputs the following to the immediate window:
a£Δ√
a 97 61
£ 163 A3
Δ 916 394
√ 8730 221A
You can remove the BOM using:
//Create a character to compare BOM
char byteOrderMark = (char)65279;
if (sourceString.ToCharArray()[0].Equals(byteOrderMark))
{
targetString = sourceString.Remove(0, 1);
}
I want to get the ASCII value of characters in a string in C#.
Everyone confer answer in this structure.
If my string has the value "9quali52ty3", I want an array with the ASCII values of each of the 11 characters.
but in console we work frankness so we get a char and print the ASCII code if i wrong so please correct my answer.
static void Main(string[] args)
{
Console.WriteLine(Console.Read());
Convert.ToInt16(Console.Read());
Console.ReadKey();
}
Why not the old fashioned easy way?
public int[] ToASCII(string s)
{
char c;
int[] cByte = new int[s.Length]; / the ASCII string
for (int i = 0; i < s.Length; i++)
{
c = s[i]; // get a character from the string s
cByte[i] = Convert.ToInt16(c); // and convert it to ASCII
}
return cByte;
}
string nomFile = "9quali52ty3";
byte[] nomBytes = Encoding.ASCII.GetBytes(nomFile);
string name = "";
foreach (byte he in nomBytes)
{
name += he.ToString("X02");
}
`
Console.WriteLine(name);
// it's` better now ;)

Categories

Resources