How to get ASCII value of string in C# - 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 ;)

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.

Xor operation between binary values in C#

My question is that i have a list of binary string like below :
list=<"1111","1010","1010","0011">
and an input string of binary value st1=1010. I want to Xor between :
st3=st1 Xor list<0>
then :
st3=st3 Xor list<1>
st3=st3Xor list <2>;
st3=st3 Xor list <3>;
where the operation will be st1 Xor with first key in keys list and the result Xor with the second key in keys list and the result Xor with the third key in keys list and so on . Can any one help me please?
i have tried this code but it does not work as i expected :
foreach (string k in keys)
{
string st1 = textBox1.text;
string st2 = k;
string st3;
st3 = "";
//i wanted to make the length of both strings st1 and st2 equal
//here if the length of st1 greater than st2
if (st1.Length > st2.Length)
{
int n = st1.Length - st2.Length;
string pad = "";
for (int j = 1; j <= n; j++)
{ pad += 0; }
string recover = pad.ToString() + st2;
//this is my Xor operation that i made for string values
for (int counter = 0; counter < st1.Length; counter++)
{
if (st1[counter] != recover[counter])
{
st3 = st3 + '1';
}
else
{ st3 = st3 + '0'; }
}
listBox4.Items.Add("Xor :" + st3.ToString());
}
//here if st1 is less than st2
else if (st1.Length < st2.Length)
{
int nn = st2.Length - st1.Length;
string ppad = "";
for (int j = 1; j <= nn; j++)
{
ppad += 0;
}
string recover = ppad.ToString() + st1;
for (int counter = 0; counter < st2.Length; counter++)
{
if (st2[counter] != recover[counter])
{
st3 = st3 + '1';
}
else
{ st3 = st3 + '0'; }
}
listBox4.Items.Add("Xor :" + st3.ToString());}
//here if st1 equal st2
else
{
for (int counter = 0; counter < st1.Length; counter++)
{
if (st1[counter] != st2[counter])
{
st3 = st3 + '1';
}
else
{ st3 = st3 + '0'; }
}
listBox4.Items.Add("Xor :" + st3.ToString());
}
}
the result that i do not expected is :
Here's one approach (Arbitrary length binary strings):
Convert the strings back to integers BigIntegers, so that we can actually get the utility of existing bitwise Xor operator (^).
Use LINQ's Aggregate to consecutively left-fold the seed value (st1) with the converted list with Xor.
Since you seem interested only in the lowest 4 bits, I've applied a mask, although if all your numbers are strictly 4 bits, this isn't actually necessary (since 0 Xor 0 stays 0)
You can convert the int back to a binary string with Convert.ToString(x, 2) and then PadLeft to replace any missing leading zeroes.
Edit - OP has changed the question from an example 4 bit number and the requirement is now to work with arbitrary length binary strings. This approach still works, but we'll need to use BigInteger (which still has an XOR ^ operator), but we need helpers to parse and format binary strings, as these aren't built into BigInteger. The BitMask and padding have also been removed, since the strings aren't fixed length - the result will have at most 1 leading zero:
var list = new List<string>{"10101010101010101101","1101010101010101011",
"1110111111010101101","11111111111111111111111111","10101010110101010101"};
var listNum = list.Select(l => BinaryStringToBigInteger(l));
var st1 = "000000001";
var seedNumber = BinaryStringToBigInteger(st1);
var chainedXors = listNum.Aggregate(seedNumber, (prev, next) => prev ^ next);
// Back to binary representation of the string
var resultString = chainedXors.ToBinaryString();
And because there's no native support for converting BigIntegers to / from binary strings, you'll need a conversion helper such as Douglas's one here:
BigInteger BinaryStringToBigInteger(string binString)
{
return binString.Aggregate(BigInteger.Zero, (prev, next) => prev * 2 + next - '0');
}
And for the reverse operation, ToBinaryString is from this helper.
32 Bit Integer answer
If the Binary strings are 32 bits or less, then a much simpler solution exists, since there are out of the box conversions to / from binary strings. The same approach should apply for 64 bit longs.
var list = new List<string>{"1111","1010","1010","0011","0011"};
var listNum = list.Select(l => Convert.ToInt32(l, 2));
// If you only want the last 4 bits. Change this to include as many bits as needed.
var bitMask = Convert.ToInt32("00000000000000000000000000001111", 2);
var st1 = "1010";
var someNum = Convert.ToInt32(st1, 2);
var chainedXors = listNum.Aggregate(someNum, (prev, next) => prev ^ next);
// If you need the result back as a 4 bit binary-string, zero padded
var resultString = Convert.ToString(chainedXors & bitMask, 2)
.PadLeft(4, '0');
Try this code:
static void Main(string[] args)
{
List<string> list = new List<string> { "1111", "1010", "1010", "0011" };
string st1 = "1010";
foreach (string item in list)
{
st1 = XorBins(st1, item);
Console.WriteLine(st1);
}
Console.ReadKey();
}
private static string XorBins(string bin1, string bin2)
{
int len = Math.Max(bin1.Length, bin2.Length);
string res = "";
bin1 = bin1.PadLeft(len, '0');
bin2 = bin2.PadLeft(len, '0');
for (int i = 0; i < len; i++)
res += bin1[i] == bin2[i] ? '0' : '1';
return res;
}
Here is an Xor method for you:
public static string Xor(string s1, string s2) {
// find the length of the longest of the two strings
int longest = Math.Max(s1.Length, s2.Length);
// pad both strings to that length. You don't need to write the padding
// logic yourself! There is already a method that does that!
string first = s1.PadLeft(longest, '0');
string second = s2.PadLeft(longest, '0');
// Enumerable.Zip takes two sequences (in this case sequences of char, aka strings)
// and lets you transform each element in the sequences. Here what
// I did was check if the two chars are not equal, in which case
// I transform the two elements to a 1, 0 otherwise
return string.Join("", Enumerable.Zip(first, second, (x, y) => x != y ? '1' : '0'));
}
You can use it like this:
Xor("1111", "1010") // 0101

`if` statement not working correctly

I am trying to make a console application for my programming class. The if statement is not working correctly. I want it to count the string length and if it's greater than 10000 or less than 0, go to the else statement. But it doesn't and continues the if statement.
static void Main(string[] args)
{
Console.WriteLine("Input a year from 0 to 10000 to determine the next year with distinct numbers");
string a = Console.ReadLine();
int MaxLength = 10000;
int MinLength = 0;
if (a.Length <= MaxLength && a.Length >= MinLength)
{
string b = a.Substring(0, 1);
string b1 = a.Substring(1, 1);
string b2 = a.Substring(2, 1);
string b3 = a.Substring(3, 1);
Console.WriteLine(b + " " + b1 + " " + b2 + " " + b3);
}
else
{
Console.WriteLine("Error");
}
Console.ReadKey();
}
You have to use int.Parse(a).
if (int.Parse(a) <= MaxLength && int.Parse(a) >= MinLength)
{
string b = a.Substring(0, 1);
string b1 = a.Substring(1, 1);
string b2 = a.Substring(2, 1);
string b3 = a.Substring(3, 1);
Console.WriteLine(b + " " + b1 + " " + b2 + " " + b3);
}
else
{
Console.WriteLine("Error");
}
Your code is checking the length of the string input - so if a user enters, for example, 100 the length will be three.
A length of a string can never be less than zero, and I very much doubt it will ever be longer than 10000.
Perhaps what you were actually trying to do is convert the user's entry to a number, while also keeping th ability to use the Substring method from the users input as a set of characters.
In which case, you want 2 variables
The original user input (a string, where you can use Substring) - a from your original code
A numerical representation of the input for which you can compare to a min & max number. val in the code below
Another consideration is that the user may enter a value which is not convertable to a number, so
A boolean indicating that the user has entered a valid number. isValidEntry in the code below
Console.WriteLine("Input a year from 0 to 10000 to determine the next year with distinct numbers");
string a = Console.ReadLine();
int MaxLength = 10000;
int MinLength = 0;
int val = 0;
bool isValidEntry = int.TryParse(a, out val);
if (isValidEntry && val <= MaxLength && val >= MinLength)
{
string b = a.Substring(0, 1);
string b1 = a.Substring(1, 1);
string b2 = a.Substring(2, 1);
string b3 = a.Substring(3, 1);
Console.WriteLine(b + " " + b1 + " " + b2 + " " + b3);
}
else
{
Console.WriteLine("Error");
}
Console.ReadKey();
I believe there is some confusion on what you are doing. Your description says you are trying to count the amount of characters in the inputed string. In which case you will need a string with more that 10000 characters to go the else statement.
However your program code claims you just want the numerical value of your string. Therefore you should try using a conversion method.
int x = int.Parse(a);
Obviously you need to do bound checking on x instead of a afterwards.

Converting string or char to int

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.

Mask out part first 12 characters of string with *?

How can I take the value 123456789012345 or 1234567890123456 and turn it into:
************2345 and ************3456
The difference between the strings above is that one contains 15 digits and the other contains 16.
I have tried the following, but it does not keep the last 4 digits of the 15 digit number and now matter what the length of the string, be it 13, 14, 15, or 16, I want to mask all beginning digits with a *, but keep the last 4. Here is what I have tried:
String.Format("{0}{1}", "************", str.Substring(11, str.Length - 12))
Something like this:
string s = "1234567890123"; // example
string result = s.Substring(s.Length - 4).PadLeft(s.Length, '*');
This will mask all but the last four characters of the string. It assumes that the source string is at least 4 characters long.
using System;
class Program
{
static void Main()
{
var str = "1234567890123456";
if (str.Length > 4)
{
Console.WriteLine(
string.Concat(
"".PadLeft(12, '*'),
str.Substring(str.Length - 4)
)
);
}
else
{
Console.WriteLine(str);
}
}
}
Easiest way: Create an extension method to extract the last four digits. Use that in your String.Format call.
For example:
public static string LastFour(this string value)
{
if (string.IsNullOrEmpty(value) || value.length < 4)
{
return "0000";
}
return value.Substring(value.Length - 4, 4)
}
In your code:
String.Format("{0}{1}", "************", str.LastFour());
In my opinion, this leads to more readable code, and it's reusable.
EDIT: Perhaps not the easiest way, but an alternative way that may produce more maintainable results. <shrug/>
Try this:
var maskSize = ccDigits.Length - 4;
var mask = new string('*', maskSize) + ccDigits.Substring(maskSize);
LINQ:
char maskBy = '*';
string input = "123456789012345";
int count = input.Length <= 4 ? 0 : input.Length - 4;
string output = new string(input.Select((c, i) => i < count ? maskBy : c).ToArray());
static private String MaskInput(String input, int charactersToShowAtEnd)
{
if (input.Length < charactersToShowAtEnd)
{
charactersToShowAtEnd = input.Length;
}
String endCharacters = input.Substring(input.Length - charactersToShowAtEnd);
return String.Format(
"{0}{1}",
"".PadLeft(input.Length - charactersToShowAtEnd, '*'),
endCharacters
);
}
Adjust the function header as required, call with:
MaskInput("yourInputHere", 4);
private string MaskDigits(string input)
{
//take first 6 characters
string firstPart = input.Substring(0, 6);
//take last 4 characters
int len = input.Length;
string lastPart = input.Substring(len - 4, 4);
//take the middle part (****)
int middlePartLenght = len - (firstPart.Length + lastPart.Length);
string middlePart = new String('*', middlePartLenght);
return firstPart + middlePart + lastPart;
}
MaskDigits("1234567890123456");
// output : "123456******3456"
Try the following:
private string MaskString(string s)
{
int NUM_ASTERISKS = 4;
if (s.Length < NUM_ASTERISKS) return s;
int asterisks = s.Length - NUM_ASTERISKS;
string result = new string('*', asterisks);
result += s.Substring(s.Length - NUM_ASTERISKS);
return result;
}
Regex with a match evaluator will do the job
string filterCC(string source) {
var x=new Regex(#"^\d+(?=\d{4}$)");
return x.Replace(source,match => new String('*',match.Value.Length));
}
This will match any number of digits followed by 4 digits and the end (it won't include the 4 digits in the replace). The replace function will replace the match with a string of * of equal length.
This has the additional benefit that you could use it as a validation algorthim too. Change the first + to {11,12} to make it match a total of 15 or 16 chars and then you can use x.IsMatch to determine validity.
EDIT
Alternatively if you always want a 16 char result just use
return x.Replace(source,new String('*',12));
// "123456789".MaskFront results in "****56789"
public static string MaskFront(this string str, int len, char c)
{
var strArray = str.ToCharArray();
for (var i = 0; i < len; i++)
{
if(i < strArray.Length)
{
strArray[i] = c;
}
else
{
break;
}
}
return string.Join("", strArray);
}
// "123456789".MaskBack results in "12345****"
public static string MaskBack(this string str, int len, char c)
{
var strArray = str.ToCharArray();
var tracker = strArray.Length - 1;
for (var i = 0; i < len; i++)
{
if (tracker > -1)
{
strArray[tracker] = c;
tracker--;
}
else
{
break;
}
}
return string.Join("", strArray);
}
Try this out:
static string Mask(string str)
{
if (str.Length <= 4) return str;
Regex rgx = new Regex(#"(.*?)(\d{4})$");
string result = String.Empty;
if (rgx.IsMatch(str))
{
for (int i = 0; i < rgx.Matches(str)[0].Groups[1].Length; i++)
result += "*";
result += rgx.Matches(str)[0].Groups[2];
return result;
}
return str;
}
Mask from start and from end with sending char
public static string Maskwith(this string value, int fromStart, int fromEnd, char ch)
{
return (value?.Length >= fromStart + fromEnd) ?
string.Concat(Enumerable.Repeat(ch, fromStart)) + value.Substring(fromStart, value.Length - (fromStart + fromEnd)) + string.Concat(Enumerable.Repeat(ch, fromEnd))
: "";
} //Console.WriteLine("mytestmask".Maskwith(2,3,'*')); **testm***
show chars from start and from end by passing value and mask the middle
public static string MasktheMiddle(this string value, int visibleCharLength, char ch)
{
if (value?.Length <= (visibleCharLength * 2))
return string.Concat(Enumerable.Repeat(ch,value.Length));
else
return value.Substring(0, visibleCharLength) + string.Concat(Enumerable.Repeat(ch, value.Length - (visibleCharLength * 2))) + value.Substring(value.Length - visibleCharLength);
} //Console.WriteLine("mytestmask".MasktheMiddle(2,'*')); Result: my******sk
How can I take the value 123456789012345 or 1234567890123456 and turn it into:
************2345 and ************3456
one more way to do this:
var result = new string('*',0,value.Length - 4) + new string(value.Skip(value.Length - 4).ToArray())
// or using string.Join
An extension method using C# 8's index and range:
public static string MaskStart(this string input, int showNumChars, char maskChar = '*') =>
input[^Math.Min(input.Length, showNumChars)..]
.PadLeft(input.Length, maskChar);
A simple way
string s = "1234567890123"; // example
int l = s.Length;
s = s.Substring(l - 4);
string r = new string('*', l);
r = r + s;

Categories

Resources