lets say I have a string that contains binary, like this:
string test = "01001010";
so I want to do something like this:
someFunc(test);
and this function would return exactly what the test variable says, but in byte form instead of string.
example:
using System;
class Program
{
static void Main()
{
Console.WriteLine(Convert.ToChar(someFunc(Console.ReadLine())));
}
}
this program prompts you to enter a byte using Console.ReadLine (which returns a string), turns it into a byte, then turns it into a char.
How could I do this?
You could write it in this way:
using System;
class Program
{
static byte someFunc(string text)
{
byte t = 0;
for (int i = 0; i < 8; i++)
t = (byte)(t * 2 + (text[i] - '0'));
return t;
}
static void Main()
{
Console.WriteLine(Convert.ToChar(someFunc(Console.ReadLine())));
}
}
But it would be useful before using someFunc() to check if string is not okey (for example, that there would be shown an error message if input is "10102010")
Use Convert.ToInt32(string, int) where string is the string you want to convert, and int is the base of the number system you want to convert from, in your case base 2 or binary. Or if you really desperately need it to be a byte, then you can use Convert.ToByte(string, int). Like so:
using System;
class Program
{
public static void Main()
{
var input = Console.ReadLine(); // 01001010
var number = Convert.ToInt32(input, 2);
Console.WriteLine(number); // prints '74'
}
}
Be warned that Convert.ToXyz() will throw an exception of type FormatException if the given input string contains character that are illegal for the given base. For base 2 that would be any character that's not a 0 or 1, you might want to catch such exceptions, or check that all characters in the input string are either a '0' or '1' beforehand
Edited:
Take char after char, add it to result byte and multiply by 2 to convert from binary to decimal (except for the last char, it should be just added).
Then return byte as char.
public static char someFunc(string bs) {
byte result = 0;
for (int i = 0; i < bs.Length - 1; i++)
{
if (bs[i].Equals('1'))
{
result += 1;
}
result *= 2;
}
if (bs[bs.Length - 1].Equals('1'))
{
result++;
}
return (char) result;
}
returns J for "01001010"
Hi this is one implementation which i use in java, but this will ork for c# as well. My be you need some syntax changes.
static int someFunc(String s){
int binary = 0x00;
for(int i=0;i<8;i++){
if(s.charAt(i) == '1')
binary =(binary<<1) | 0x01;
else if(s.charAt(i) == '0')
binary =(binary<<1) | 0x00;
}
return binary;
}
Related
I have a large float that I want to convert into a string with commas without rounding.
Here is what I have:
String.Format("{0:#,###}", val);
This turns 17154177 into 17,154,180
I would like to keep the commas but not round at the end using c#.
This may be what you're looking for
using System;
class MainClass {
public static void Main (string[] args) {
float original = 17154177;
// 1. Convert the number to a string
string value = original.ToString("R");
// 2. Reverse the string
string reversed = Reverse(value);
// 3. Add the comma on each third number, backwards
string formatted = "";
for(int i = 0; i < reversed.Length; i++) {
if ((i+1) % 3 == 0) {
formatted += reversed[i] + ",";
} else {
formatted += reversed[i];
}
}
// 4. Reverse it back to the original order
formatted = Reverse(formatted);
Console.WriteLine (formatted);
}
/* Reverses a string */
public static string Reverse(string text)
{
char[] cArray = text.ToCharArray();
string reverse = String.Empty;
for (int i = cArray.Length - 1; i > -1; i--)
{
reverse += cArray[i];
}
return reverse;
}
}
I got the reverse method from this question.
Change your data type to decimal (28-29 significant digits) to have higher precision compared to float (7 digits).
Or you can change it to var. It will let the compiler figure out the best data type to use.
var number = 17154177;
Console.WriteLine(String.Format("{0:#,###}", number));
See this fiddler link, working code
I'm trying to calculate the number of digit before the floating points. for example
input: 123.4
expected output: 3
my actual output: 5
I'm sure there is something wrong with the digit.equals(".") since the program does not break out of the loop.
this is my code:
public class Program
{
public static void Main()
{
Console.WriteLine(HowManyDigit(123.4));
}
public static Int32 HowManyDigit(Double number)
{
string x = number.ToString();
var counter = 0;
for (int i = 0; i < x.Length; i++)
{
var digit = x[i];
//Console.WriteLine(counter);
if (digit.Equals("."))
{
break;
}
else
{
counter++;
}
}
return counter;
}
}
The reason your code does not work breaks down to this logic:
var digit = x[i];
if (digit.Equals("."))
{
break;
}
The char digit will never be equal to the string "."
If you change your code to:
//Note that I use a char, indicated by ''
if (x[i].Equals('.'))
{
break;
}
Or simply:
if (x[i] == '.')
{
break;
}
Either of those two methods will give you a drastically different result from your current code.
That being said, this method is not really the best way of doing what you want. You can simply use IndexOf() to get the exact number you want:
public static int HowManyDigit(double number)
{
return number.ToString().IndexOf('.');
}
Fiddle here
Just compute the logarithm of base 10 and then convert to integer with floor.
n = Math.Floor(Math.Log10(x))+1;
Try this x.IndexOf('.') this will be your answer
Replace this:
if (digit.Equals("."))
With this:
if (digit.Equals('.'))
Now your output should be 3.
Here is a LINQ solution:
double number = 123.4;
var result = number.ToString().TakeWhile(x => char.IsDigit(x)).Count();
I work on a project in C# which requires to use arabic numbers, but then it must store as integer in database, I need a solution to convert arabic numbers into int in C#.
Any solution or help please?
thanks in advance
From comments:
I have arabic numbers like ١،٢،٣،٤... and must convert to 1,2,3, or ٢٣٤ convert to 234
Updated: You can use StringBuilder for memory optimization.
private static string ToEnglishNumbers(string input)
{
StringBuilder sbEnglishNumbers = new StringBuilder(string.Empty);
for (int i = 0; i < input.Length; i++)
{
if (char.IsDigit(input[i]))
{
sbEnglishNumbers.Append(char.GetNumericValue(input, i));
}
else
{
sbEnglishNumbers.Append(input[i].ToString());
}
}
return sbEnglishNumbers.ToString();
}
Original Answer: use this Method
private string toEnglishNumber(string input)
{
string EnglishNumbers = "";
for (int i = 0; i < input.Length; i++)
{
if (Char.IsDigit(input[i]))
{
EnglishNumbers += char.GetNumericValue(input, i);
}
else
{
EnglishNumbers += input[i].ToString();
}
}
return EnglishNumbers;
}
Unfortunately it is not yet possible to parse the complete string representation by passing in an appropriate IFormatProvider(maybe in the upcoming versions). However, the char type has a GetNumericValue method which converts any numeric Unicode character to a double. For example:
double two = char.GetNumericValue('٢');
Console.WriteLine(two); // prints 2
You could use it to convert one digit at a time.
Arabic digits like ١،٢،٣،٤ in unicode are encoded as characters in the range 1632 to 1641. Subtract the unicode for arabic zero (1632) from the unicode value of each arabic digit character to get their digital values. Multiply each digital value with its place value and sum the results to get the integer.
Alternatively use Regex.Replace to convert the string with Arabic digits into a string with decimal digits, then use Int.Parse to convert the result into an integer.
A simple way to convert Arabic numbers into integer
string EnglishNumbers="";
for (int i = 0; i < arabicnumbers.Length; i++)
{
EnglishNumbers += char.GetNumericValue(arabicnumbers, i);
}
int convertednumber=Convert.ToInt32(EnglishNumbers);
This is my solution :
public static string arabicNumToEnglish(string input)
{
String[] map={"٠","١","٢","٣","٤","٥","٦","٧","٨","٩"};
for (int i = 0; i <= 9; i++)
{
input=input.Replace(map[i],i.ToString());
}
return input;
}
to get the value of a digit, substract the zero character from it, e.g in normal numeric, '1'-'0' = 1, '2'-'0' = 2. etc.
For multidigit number you can use something like this
result =0;
foreach(char digit in number)
{
result *= 10; //shift the digit, multiply by ten for each shift
result += (digit - '0)'; //add the int value of the current digit.
}
just replace the '0' with the arabic zero if your number uses Arabic character. This works for any numeric symbols, as long as 0-9 in that symbol system are encoded consecutively.
I know this question is a bit old, however I faced similar case in one of my projects and passed by this question and decided to share my solution which did work perfectly for me, and hope it will serve others the same.
private string ConvertToWesternArbicNumerals(string input)
{
var result = new StringBuilder(input.Length);
foreach (char c in input.ToCharArray())
{
//Check if the characters is recognized as UNICODE numeric value if yes
if (char.IsNumber(c))
{
// using char.GetNumericValue() convert numeric Unicode to a double-precision
// floating point number (returns the numeric value of the passed char)
// apend to final string holder
result.Append(char.GetNumericValue(c));
}
else
{
// apend non numeric chars to recreate the orignal string with the converted numbers
result.Append(c);
}
}
return result.ToString();
}
now you can simply call the function to return the western Arabic numerals.
try this extension:
public static class Extension
{
public static string ToEnglishNumbers(this string s)
{
return s.Replace("۰", "0").Replace("۱", "1").Replace("۲", "2").Replace("۳", "3").Replace("۴", "4")
.Replace("۵", "5").Replace("۶", "6").Replace("۷", "7").Replace("۸", "8").Replace("۹", "9");
}
public static int ToNumber(this string s)
{
if (int.TryParse(s.ToEnglishNumbers(), out var result))
{
return result;
}
return -1;
}
public static string ToArabicNumbers(this string s)
{
return s.Replace("0", "۰").Replace("1", "۱").Replace("2", "۲").Replace("3", "۳").Replace("4", "۴")
.Replace("5", "۵").Replace("6", "۶").Replace("7", "۷").Replace("8", "۸").Replace("9", "۹");
}
}
Am very (very) new to C#, I would really appreciate your assistance to code in C# a program that allows me to calculate the sum of two ASCII characters in their numeric equivalence, any ASCII character.
I have tried declaring it as an int: int A = 60,etc. Also:
char a = 'A';
int i = (int) a;
Console.WriteLine("{0}", i);
I have two days trying to do it, but my brain is not working.
Thanks!!!!
You can add the characters and assign them to an integer
char char1 = 'A';
char char2 = 'F';
int value = char1 + char2;
int sumOfAsciiCodes = Convert.ToInt32('A') + Convert.ToInt32('F');
You can create a reusable method (GetAscii()) for that task:
private void Init()
{
var result = GetAscii("AF");
int sum = 0;
foreach (var itm in result)
{
// show each ascii value
Console.WriteLine(itm.ToString());
sum += (int)itm;
}
// sum all values
Console.WriteLine(sum.ToString());
}
private byte[] GetAscii(string value)
{
byte[] asciiBytes = Encoding.ASCII.GetBytes(value);
return asciiBytes;
}
If they are char types just add them together:
static int Add(char a, char b)
{
var c = a + b;
return c;
}
If they are string types you can use the following code (after you imported the "System.Linq" namespace) (updated with ckuri's suggestion):
static int Add(string a, string b)
{
var c = (a + b).Select(f=>(int)f).Sum();
return c;
}
Demo: https://dotnetfiddle.net/qbVWIP
Below is my string in C# which I am converting it to Character array & in need to get the ASCII value of each character in the string.
static void Main(string[] args)
{
string s = "Test";
var arr = s.ToCharArray();
foreach(var a in arr)
{
var n = Encoding.ASCII.GetByteCount(a.ToString());
Console.WriteLine(a);
Console.WriteLine(n);
}
}
This outputs as
T
1
e
1
s
1
t
1
On googling I got number of links but none of them suffice my need.
How to get ASCII value of string in C#
https://www.codeproject.com/Questions/516802/ConvertingpluscharsplustoplusASCIIplusinplusC
I am in need to get the ASCII value of each character in string.???
Any help/suggestion highly appreciated.
A string can be directly enumerated to a IEnumerable<char>. And each char can be casted to a integer to see its UNICODE "value" (code point). UTF-16 maps the 128 characters of ASCII (0-127) to the UNICODE code points 0-127 (see for example https://en.wikipedia.org/wiki/Code_point), so you can directly print this number.
string s = "Test";
foreach (char a in s)
{
if (a > 127)
{
throw new Exception(string.Format(#"{0} (code \u{1:X04}) is not ASCII!", a, (int)a));
}
Console.WriteLine("{0}: {1}", a, (int)a);
}
GetByteCount will return the count of bytes used, so for each character it will be 1 byte.
Try GetBytes
static void Main(string[] args)
{
string s = "Test";
var n = ASCIIEncoding.ASCII.GetBytes(s);
for (int i = 0; i < s.Length; i++)
{
Console.WriteLine($"Char {s[i]} - byte {n[i]}");
}
}
Every character is represented in the ASCII table with a value between 0 and 127. Converting the chars to an Integer you will be able to get the ASCII value.
static void Main(string[] args)
{
string s = "Test";
for (int i = 0; i < s.Length; i++)
{
//Convert one by one every leter from the string in ASCII value.
int value = s[i];
Console.WriteLine(value);
}
}
You're asking for the byte count when you should be asking for the bytes themselves. Use Encoding.ASCII.GetBytes instead of Encoding.ASCII.GetByteCount. Like in this answer: https://stackoverflow.com/a/400777/3129333
Console.WriteLine(a);
Console.WriteLine(((int)a).ToString("X"));
You need to convert in int and then in hex.
GetByteCount will return the count of bytes used, so for each character it will be 1.
You can read also: Need to convert string/char to ascii values