Making formulas in c# to convert dollar amount into denominations - c#
I'm making a program to convert any input amount into denominations of twenties, tens, fives, and ones. Here's what I'm having trouble with:
int twenties = dollar/20;
int tens = twenties/2;
int fives = tens/2;
int ones = fives/5;
Dollar is the input amount, the twenties expression seems to be the only one that comes out right. For example: I input 161 and it comes out as 161 is equal to 8 twenties, 4 tens, 2 fives, and 0 ones. But it should be coming out as 161 is equal to 8 twenties, 0 tens, 0 fives, and 1 ones. I know there is a really simple answer to this but I'm just not getting it, thanks guys.
You need to work with the remainder after removing those denominations. The easiest way to get the remainder is the modulus operator, like this...
int dollar = 161;
int twenties = dollar / 20;
int remainder = dollar % 20;
int tens = remainder / 10;
remainder = remainder % 10;
int fives = remainder / 5;
remainder = remainder % 5;
int ones = remainder;
The above approach does not modify the original amount. By refactoring that into a method, it makes it easier to reuse with different denominations:
public int RemoveDenomination(int denomination, ref int amount)
{
int howMany = amount / denomination;
amount = amount % denomination;
return howMany;
}
...which you could use like this...
int dollar = 161;
int hundreds = RemoveDenomination(100, ref dollar);
int fifties = RemoveDenomination(50, ref dollar);
int twenties = RemoveDenomination(20, ref dollar);
int tens = RemoveDenomination(10, ref dollar);
int fives = RemoveDenomination(5, ref dollar);
int ones = dollar;
This approach does modify the dollar value. So if you don't want to change it, make a copy of it in another variable, and work on the copy.
You have to use the remainder and subtract until the remainder becomes 0;
int amount = 161, temp = 0;
int[] denomination = { 20, 10, 5, 1 }; // you can use enums also for
// readbility
int[] count = new int[denomination.Length];
while (amount > 0)
{
count[temp] = amount / denomination[temp];
amount -= count[temp] * denomination[temp];
temp ++;
}
Another option is to use linq:
int[] denominations = new [] { 20, 10, 5, 1 };
List<int> result =
denominations
.Aggregate(new { Result = new List<int>(), Remainder = 161 }, (a, x) =>
{
a.Result.Add(a.Remainder / x);
return new { a.Result, Remainder = a.Remainder % x };
})
.Result;
That returns a list with the values { 8, 0, 0, 1 }.
Alternatively you could do this:
public static Dictionary<string, int> Denominations(int amount)
{
var denominations = new Dictionary<string, int>();
denominations["twenties"] = amount / 20;
amount = amount % 20;
denominations["tens"] = amount / 10;
amount = amount % 10;
denominations["fives"] = amount / 5;
amount = amount % 5;
denominations["ones"] = amount;
return denominations;
}
This console app illustrates a possible solution:
internal static class Program
{
internal static void Main()
{
var results = GetDenominationValues();
foreach (var result in results)
{
Console.WriteLine($"{result.Key} - {result.Value}");
}
Console.ReadLine();
}
private static Dictionary<int, int> GetDenominationValues()
{
var amount = 161;
var denominations = new[] { 20, 10, 5, 1 };
var results = new Dictionary<int, int>();
foreach (var denomination in denominations)
{
results.Add(denomination, amount / denomination);
amount = amount % denomination;
if (amount == 0) break;
}
return results;
}
}
The key difference is in the line:
amount = amount % denomination;
Which uses the remainder of the previous division in the subsequent calculations.
If the division is greater than zero pass on the remainder (using the modulo operator, %) else pass on the original value to the next division in line. Repeat until no more division left.
Also, divide tens with 10, fives with 5 and ones with 1.
Please use below function that returns dictionary
public static Dictionary<string, int> Denominations(int amount)
{
Dictionary<string, int> denominations = new Dictionary<string, int>() { { "twenties", 0 }, { "tens", 0 }, { "fives", 0 }, { "ones", 0 } };
int twenties, tens, fives, ones;
if (amount >= 20)
{
twenties = amount/20;
denominations["twenties"] = twenties;
amount -= twenties * 20;
}
if (amount >= 10)
{
tens = amount/10;
denominations["tens"] = tens;
amount -= tens * 10;
}
if (amount >= 5)
{
fives = amount/5;
denominations["fives"] = fives;
amount -= fives * 5;
}
if (amount >= 1)
{
ones = amount;
denominations["ones"] = ones;
}
return denominations;
}
You want Code number to text ?
MoneyExt mne = new MoneyExt();
string textamount;
textamount = mne.ConvertNumberToENG(10000);
using System;
public class MoneyExt
{
public string ConvertNumberToENG(int amount)
{
var dollars, cents, temp;
var decimalPlace, count;
string[] place = new string[10];
place[2] = " Thousand ";
place[3] = " Million ";
place[4] = " Billion ";
place[5] = " Trillion ";
// String representation of amount.
amount = amount.Trim();
amount = amount.Replace(",", "");
// Position of decimal place 0 if none.
decimalPlace = amount.IndexOf(".");
// Convert cents and set string amount to dollar amount.
if (decimalPlace > 0)
{
cents = GetTens(ref amount.Substring(decimalPlace + 1).PadRight(2, "0").Substring(0, 2));
amount = amount.Substring(0, decimalPlace).Trim();
}
count = 1;
while (amount != "")
{
temp = GetHundreds(amount.Substring(Math.Max(amount.Length, 3) - 3));
if (temp != "")
dollars = temp + place[count] + dollars;
if (amount.Length > 3)
amount = amount.Substring(0, amount.Length - 3);
else
amount = "";
count = count + 1;
}
switch (dollars)
{
case "One":
{
dollars = "One Bath";
break;
}
default:
{
dollars = dollars + " Bath";
break;
}
}
// Select Case cents
// ' Case ""
// ' cents = " and No Cents"
// Case "One"
// cents = " and One Satang"
// Case Else
// cents = " and " & cents & " Satang"
// End Select
ConvertNumberToENG = dollars + cents;
}
// Converts a number from 100-999 into text
public string GetHundreds(string amount)
{
string Result;
if (!int.Parse(amount) == 0)
{
amount = amount.PadLeft(3, "0");
// Convert the hundreds place.
if (amount.Substring(0, 1) != "0")
Result = GetDigit(ref amount.Substring(0, 1)) + " Hundred ";
// Convert the tens and ones place.
if (amount.Substring(1, 1) != "0")
Result = Result + GetTens(ref amount.Substring(1));
else
Result = Result + GetDigit(ref amount.Substring(2));
GetHundreds = Result;
}
}
// Converts a number from 10 to 99 into text.
private string GetTens(ref string TensText)
{
string Result;
Result = ""; // Null out the temporary function value.
if (TensText.StartsWith("1"))
{
switch (int.Parse(TensText))
{
case 10:
{
Result = "Ten";
break;
}
case 11:
{
Result = "Eleven";
break;
}
case 12:
{
Result = "Twelve";
break;
}
case 13:
{
Result = "Thirteen";
break;
}
case 14:
{
Result = "Fourteen";
break;
}
case 15:
{
Result = "Fifteen";
break;
}
case 16:
{
Result = "Sixteen";
break;
}
case 17:
{
Result = "Seventeen";
break;
}
case 18:
{
Result = "Eighteen";
break;
}
case 19:
{
Result = "Nineteen";
break;
}
default:
{
break;
}
}
}
else
{
switch (int.Parse(TensText.Substring(0, 1)))
{
case 2:
{
Result = "Twenty ";
break;
}
case 3:
{
Result = "Thirty ";
break;
}
case 4:
{
Result = "Forty ";
break;
}
case 5:
{
Result = "Fifty ";
break;
}
case 6:
{
Result = "Sixty ";
break;
}
case 7:
{
Result = "Seventy ";
break;
}
case 8:
{
Result = "Eighty ";
break;
}
case 9:
{
Result = "Ninety ";
break;
}
default:
{
break;
}
}
Result = Result + GetDigit(ref TensText.Substring(1, 1)); // Retrieve ones place.
}
GetTens = Result;
}
// Converts a number from 1 to 9 into text.
private string GetDigit(ref string Digit)
{
switch (int.Parse(Digit))
{
case 1:
{
GetDigit = "One";
break;
}
case 2:
{
GetDigit = "Two";
break;
}
case 3:
{
GetDigit = "Three";
break;
}
case 4:
{
GetDigit = "Four";
break;
}
case 5:
{
GetDigit = "Five";
break;
}
case 6:
{
GetDigit = "Six";
break;
}
case 7:
{
GetDigit = "Seven";
break;
}
case 8:
{
GetDigit = "Eight";
break;
}
case 9:
{
GetDigit = "Nine";
break;
}
default:
{
GetDigit = "";
break;
}
}
}
}
Related
how to convert series of integers into ordinals in C#
i am having a texbox1 with series of integers i would like to know if their is any way i can apply the conversion of these integers into ordinals. below is what i have tried: when my button convert is clicked with code: private void btnconvert_Click(object sender, RoutedEventArgs e) { foreach (int num in txtresults.ToString()) { string[] parts = txtresults.Text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); double[] numbers = parts.Select(p => double.Parse(p)).ToArray(); double maximum = numbers.Max(); int position = Array.IndexOf(numbers, maximum); parts[position] = **Ordinal(num);** txtresults.Text = string.Join(" ", parts); } } this is my method of conversion public static string **Ordinal(int num)** { if (num <= 0) return num.ToString(); switch (num % 100) { case 11: case 12: case 13: return num + "th"; } switch (num % 10) { case 1: return num + "st"; case 2: return num + "nd"; case 3: return num + "rd"; default: return num + "th"; } } can i be thought how to do it right please (thanks in advance) (am using c# in wpf)
Can I Set Diaper SizeLevelNumber & BrandLevelNumber using an array or different Method?
Here's a small program to tell our employee's the price of our diapers. Is there a way such as an int array or an optimized way to set brandLevelNumber & sizeLevelNumber to the selected items in the brandComboBox & the sizeComboBox? Also, do you guys think there's a better way for the method calculatePricePerDiaper() to work than a switch within a switch, or any other suggestions at all? class Diaper { public string brandLevel; public string sizeLevel; public int brandLevelNumber; public int sizeLevelNumber; public string[] brands = {"Earth's Best", "Huggies Snug & Dry", "Huggies Snugglers & Movers", "Luvs", "Pampers Baby Dry", "Pampers Swaddlers & Cruisers", "Seventh Generation", "Store"}; public string[] size = {"Size 1", "Size 2", "Size 3", "Size 4", "Size 5", "Size 6 & 7", "Size N","2T-3T", "3T-4T", "4T-5T","Big Kids" }; public double count; public double price; private double pricePerDiaper; public double finalPrice; public double calculatePricePerDiaper() { switch (brandLevelNumber) { case 0: switch (sizeLevelNumber) { case 1: if (count > 0 && count < 50) pricePerDiaper = 0.12; if (count > 50 && count <= 160) pricePerDiaper = 0.11; if (count > 160) pricePerDiaper = 0.10; break; case 2: if (count > 0 && count <= 42) pricePerDiaper = 0.13; if (count > 42 && count <=105) pricePerDiaper = 0.12; if (count > 150) pricePerDiaper = 0.11; break; case 3: if (count > 0 && count <=36) pricePerDiaper = 0.16; if (count >36) pricePerDiaper = 0.12; break; case 4: if (count > 0 && count <=31) pricePerDiaper = 0.18; if (count > 31 && count <=85) pricePerDiaper = 0.15; if (count >85) pricePerDiaper = 0.14; break; case 5: if (count > 0 && count <=28) pricePerDiaper = 0.21; if (count > 28 && count <= 100) pricePerDiaper = 0.17; if (count > 100) pricePerDiaper = 0.16; break; case 6: if (count > 0 && count <=25) pricePerDiaper = 0.24; if (count > 25) pricePerDiaper = 0.20; break; case 7: if (count > 0 && count <=50) pricePerDiaper = 0.12; if (count > 50) pricePerDiaper = 0.11; break; case 8: if (count > 0 && count <=30) pricePerDiaper = 0.23; if (count >30 && count <= 160) pricePerDiaper = 0.22; break; case 9: if (count > 0 && count <=25) pricePerDiaper = 0.26; if (count > 25 && count <= 55) pricePerDiaper = 0.25; if (count > 61) pricePerDiaper = 0.24; break; case 10: if (count > 0 && count <=22) pricePerDiaper = 0.32; if (count > 22 && count <= 40) pricePerDiaper = 0.31; if (count > 40 && count <= 60) pricePerDiaper = 0.29; if (count>60) pricePerDiaper = 0.27; break; case 11: if (count > 0 && count <=20) pricePerDiaper = 0.41; if (count > 20 && count <= 37) pricePerDiaper = 0.37; if (count >37) pricePerDiaper = 0.36; break; } break; } return pricePerDiaper; } public double calculatePrice(double pricePerDiaper, double count) { price = pricePerDiaper * count; return price; } } public partial class Form1 : Form { Diaper item = new Diaper(); public Form1() { InitializeComponent(); brandComboBox.DataSource = item.brands; sizeComboBox.DataSource = item.size; } private void Form1_Load(object sender, EventArgs e) { //Make the comboboxes appear empty at initial load //brandComboBox.SelectedItem = null; //sizeComboBox.SelectedItem = null; } private void countTextBox_TextChanged(object sender, EventArgs e) { //So exception isn't thrown if user deletes countTextBox.Text string i = countTextBox.Text; if (double.TryParse(i, out item.count)) item.count = Convert.ToDouble(countTextBox.Text); } private void doneButton_Click(object sender, EventArgs e) { item.finalPrice=(item.calculatePrice(item.calculatePricePerDiaper(), Convert.ToDouble(countTextBox.Text))); priceLabel.Text = "$" + item.finalPrice; } private void brandComboBox_SelectedIndexChanged(object sender, EventArgs e) { item.brandLevel = (string)brandComboBox.SelectedItem; switch (item.brandLevel) { case "Huggies Snug & Dry": case "Pampers Baby Dry": item.brandLevelNumber = 0; break; case "Earth's Best": case "Huggies Snugglers & Movers": case "Pampers Swaddlers & Cruisers": case "Seventh Generation": item.brandLevelNumber = 1; break; case "Luvs": item.brandLevelNumber = 2; break; case "Store": item.brandLevelNumber = 3; break; } } private void sizeComboBox_SelectedIndexChanged(object sender, EventArgs e) { item.sizeLevel = (string)sizeComboBox.SelectedItem; switch (item.sizeLevel) { case "Size 1": item.sizeLevelNumber = 1; break; case "Size 2": item.sizeLevelNumber = 2; break; case "Size 3": item.sizeLevelNumber = 3; break; case "Size 4": item.sizeLevelNumber = 4; break; case "Size 5": item.sizeLevelNumber = 5; break; case "Size 6 & 7": item.sizeLevelNumber = 6; break; case "Size N": item.sizeLevelNumber = 7; break; case "2T-3T": item.sizeLevelNumber = 8; break; case "3T-4T": item.sizeLevelNumber = 9; break; case "4T-5T": item.sizeLevelNumber = 10; break; case "Big Kids": item.sizeLevelNumber = 11; break; } } } }
I would recommend using arrays of classes to store your info. class DiaperBrandClass { public string BrandName; public int BrandLevelNumber; public DiaperBrandClass(string brandName, int brandLevel) { this.BrandName = brandName; this.BrandLevelNumber = brandLevel; } } class DiaperSizeClass { public int SizeLevelNumber; public string SizeDescription; // This could be made an enum public float BasePrice; public Dictionary<int, float> Discounts; public DiaperSizeClass(int sizeLevel, float basePrice, Dictionary<int, float> discounts, string description) { this.SizeLevelNumber = sizeLevel; this.BasePrice = basePrice; this.Discounts = discounts; this.SizeDescription = description; } } class DiaperBrandLevelClass { public DiaperSizeClass[] DiaperSizes; public DiaperBrandLevelClass(DiaperSizeClass[] diaperSizes) { this.DiaperSizes = diaperSizes; } } Then you can define each diaper either at design time or runtime. Example at design time: // We have 4 brand levels DiaperBrandLevelClass[] DiaperBrandLevels = new DiaperBrandLevelClass[4]; // We would create the 10 DiaperSizeLevels for EACH of the 4 DiaperBrandLevels DiaperSizeClass[] DiaperSizeLevels = new DiaperSizeClass[10]; // Brand Level #0 (the 'Drys') DiaperBrandLevels[0] = new DiaperBrandLevelClass(DiaperSizeLevels); // DiaperBrandLevels[0] - Size level #0 ("Size 1") DiaperSizeLevels[0] = new DiaperSizeClass( 0, 0.12f, new Dictionary<int, float>() { {50, 0.01}, // Anything above 50 gets a 0.01 discount {160, 0.02} // Anything above 160 gets a 0.02 discount }, "Size 1" ); // Size level #1 ("Size 2") DiaperSizeLevels[1] = new DiaperSizeClass( 1, 0.13f, new Dictionary<int, float>() { {42, 0.01}, // Anything above 50 gets a 0.01 discount {105, 0.02} // Anything above 160 gets a 0.02 discount }, "Size 2" ); // ... for Size Levels #2-9 ... // ... repeat the same as above for the other BrandLevels ... You would also create each brand: DiaperBrandClass[] DiaperBrands = new DiaperBrandClass[8]; DiaperBrands[0] = new DiaperBrandClass("Earth's Best", 1); DiaperBrands[1] = new DiaperBrandClass("Huggies Snug & Dry", 0); // ... You can then use: int SelectedBrandLevel = DiaperBrands[brandComboBox.Index].BrandLevelNumber; float BasePrice = DiaperBrandLevels[SelectedBrandLevel].DiaperSizes[sizeComboBox.Index].BasePrice; float Discount = DiaperBrandLevels[SelectedBrandLevel].DiaperSizes[sizeComboBox.Index].Discounts[NumberOfDiapers]; Of course no error checking has been included and this was written with no compiler or IDE nearby so there may be mistakes, but the basic idea is there. The bonus to this method is that you could create a text/xml file that holds all the brands, prices, levels, etc that the program could load so you wouldn't need to recompile the code every time a price changed. Hard coding stuff like that needs to be avoided (but is fine for test purposes). EDIT: Recommend that if you use text files have a comment character such as #. A brand file could be as simple as each line containing the name and brand level, such as: # List all brands using "<name>", <brand level> "Earth's Best", 1 "Huggies Snug & Dry", 0 Then you could create brand level files which would hold the pricing of each level (possibly in 2 lines, the file setup is your choice): # List each size as <size level>, <base price>, "<description>" on first line # and (<threshold1>, <discount1>), (<threshold2>, <discount2>), etc on second 0, 0.12f, "Size 1" (50, 0.01), (160, 0.02) 1, 0.13f, "Size 2" (42, 0.01), (105, 0.02) Something like this. How you layout the files is your choice, just a basic idea for you. You can also google XML files and C# code to read/write XML files.
What is the the Correct way of sending DateTime data for SNMPV2 using SNMPSHARPNET?
What is the correct way to send DateTime in UTC to a SNMPV2 event using SNMPSHARPNET ? http://www.snmpsharpnet.com/ We have been using TimeTicks AsnType but have run into issues of data over 29 and half days. This is the code for reference : AsnType newMIBValue = null; if (!string.IsNullOrEmpty(MIBValueString)) { switch (DataType) { case MIBDataType.DateAndTime: //newMIBValue = new TimeTicks(MIBValueString); newMIBValue = ConvertDateTimeToOctetString(MIBValueString); break; case MIBDataType.SnmpAdminString: newMIBValue = new OctetString(MIBValueString); break; case MIBDataType.TimeTicks: newMIBValue = new TimeTicks(MIBValueString); break; case MIBDataType.IPAddress: newMIBValue = new IpAddress(MIBValueString); break; case MIBDataType.Integer: newMIBValue = new Integer32(MIBValueString); break; default: break; } }
Use OCTET STRING for datetime stuff. TimeTicks is a non-negative integer which specifies the elapsed time between two events, in units of hundredth of a second.
A colleague of mine helped me put this code. Apparently we have send a byte array of hex values per SNMP specification. private OctetString ConvertStringToOctetString(DateTime dateTimeValueInUTCDateAndTime) { var yearInString = dateTimeValueInUTCDateAndTime.Year.ToString("X"); byte[] bytesArray = ConvertToByteArray(string.Format("{0}{1}{2}{3}{4}{5}{6}", yearInString, dateTimeValueInUTCDateAndTime.Month.ToString("X").PadLeft(2, '0'), dateTimeValueInUTCDateAndTime.Day.ToString("X").PadLeft(2, '0'), dateTimeValueInUTCDateAndTime.Hour.ToString("X").PadLeft(2, '0'), dateTimeValueInUTCDateAndTime.Minute.ToString("X").PadLeft(2, '0'), dateTimeValueInUTCDateAndTime.Second.ToString("X").PadLeft(2, '0'), "00" )); return new OctetString(bytesArray); } public byte[] ConvertToByteArray(string value) { byte[] bytes = null; if (String.IsNullOrEmpty(value)) bytes = null; else { int string_length = value.Length; int character_index = (value.StartsWith("0x", StringComparison.Ordinal)) ? 2 : 0; // Does the string define leading HEX indicator '0x'. Adjust starting index accordingly. int number_of_characters = string_length - character_index; bool add_leading_zero = false; if (0 != (number_of_characters % 2)) { add_leading_zero = true; number_of_characters += 1; // Leading '0' has been striped from the string presentation. } bytes = new byte[number_of_characters / 2]; // Initialize our byte array to hold the converted string. int write_index = 0; if (add_leading_zero) { bytes[write_index++] = FromCharacterToByte(value[character_index], character_index); character_index += 1; } for (int read_index = character_index; read_index < value.Length; read_index += 2) { byte upper = FromCharacterToByte(value[read_index], read_index, 4); byte lower = FromCharacterToByte(value[read_index + 1], read_index + 1); bytes[write_index++] = (byte)(upper | lower); } } return bytes; } private byte FromCharacterToByte(char character, int index, int shift = 0) { byte value = (byte)character; if (((0x40 < value) && (0x47 > value)) || ((0x60 < value) && (0x67 > value))) { if (0x40 == (0x40 & value)) { if (0x20 == (0x20 & value)) value = (byte)(((value + 0xA) - 0x61) << shift); else value = (byte)(((value + 0xA) - 0x41) << shift); } } else if ((0x29 < value) && (0x40 > value)) value = (byte)((value - 0x30) << shift); else throw new InvalidOperationException(String.Format("Character '{0}' at index '{1}' is not valid alphanumeric character.", character, index)); return value; }
How to read first 4 and last 4 bits from byte?
C# how to read first 4 and last 4 bits from byte ?
Use bitwise AND and shifts, like this: byte b = 0xAB; var low = b & 0x0F; var high = b >> 4;
I would prefer simply using this - byte a = 68; byte high_bits = a>>4; byte low_bits = a&15;
In a convenient struct: Usage var hb = new HalvedByte(5, 10); hb.Low -= 3; hb.High += 3; Console.Write(string.Format("{0} / {1}", hb.Low, hb.High)); // 2, 13 Code public struct HalvedByte { public byte Full { get; set; } public byte Low { get { return (byte)(Full & 0x0F); } set { if (value >= 16) { throw new ArithmeticException("Value must be between 0 and 16."); } Full = (byte)((High << 4) | (value & 0x0F)); } } public byte High { get { return (byte)(Full >> 4); } set { if (value >= 16) { throw new ArithmeticException("Value must be between 0 and 16."); } Full = (byte)((value << 4) | Low); } } public HalvedByte(byte full) { Full = full; } public HalvedByte(byte low, byte high) { if (low >= 16 || high >= 16) { throw new ArithmeticException("Values must be between 0 and 16."); } Full = (byte)((high << 4) | low); } } Bonus: Array (Untested) If you ever need to use an array of these half bytes, this will simplify accessing: public class HalvedByteArray { public int Capacity { get; private set; } public HalvedByte[] Array { get; private set; } public byte this[int index] { get { if (index < 0 || index >= Capacity) { throw new IndexOutOfRangeException(); } var hb = Array[index / 2]; return (index % 2 == 0) ? hb.Low : hb.High; } set { if (index < 0 || index >= Capacity) { throw new IndexOutOfRangeException(); } var hb = Array[index / 2]; if (index % 2 == 0) { hb.Low = value; } else { hb.High = value; } } } public HalvedByteArray(int capacity) { if (capacity < 0) { throw new ArgumentException("Capacity must be positive.", "capacity"); } Capacity = capacity; Array = new HalvedByte[capacity / 2]; } }
Simple method to do it. Example use : A: 10101110 B: 00001110 Get last 4 bits from A, so that output is like B getBitRange(10101110, 0, 4); //gets a bits from a byte, and return a byte of the new bits byte getBitRange(byte data, int start, int _end){ //shift binary to starting point of range byte shifted = (data >> start); //calculate range length (+1 for 0 index) int rangeLength = (_end-start)+1; //get binary mask based on range length byte maskBinary; switch (rangeLength){ case 1: maskBinary = 0b00000001; break; case 2: maskBinary = 0b00000011; break; case 3: maskBinary = 0b00000111; break; case 4: maskBinary = 0b00001111; break; case 5: maskBinary = 0b00011111; break; case 6: maskBinary = 0b00111111; break; case 7: maskBinary = 0b01111111; break; case 8: maskBinary = 0b11111111; break; default: // default statements Serial.println("Error: Range length too long!!"); } //cancel out byte finalByte = (shifted & maskBinary); return finalByte; }
How to convert numbers between hexadecimal and decimal
How do you convert between hexadecimal numbers and decimal numbers in C#?
To convert from decimal to hex do... string hexValue = decValue.ToString("X"); To convert from hex to decimal do either... int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber); or int decValue = Convert.ToInt32(hexValue, 16);
Hex -> decimal: Convert.ToInt64(hexString, 16); Decimal -> Hex string.Format("{0:x}", intValue);
It looks like you can say Convert.ToInt64(value, 16) to get the decimal from hexdecimal. The other way around is: otherVar.ToString("X");
If you want maximum performance when doing conversion from hex to decimal number, you can use the approach with pre-populated table of hex-to-decimal values. Here is the code that illustrates that idea. My performance tests showed that it can be 20%-40% faster than Convert.ToInt32(...): class TableConvert { static sbyte[] unhex_table = { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1 ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 }; public static int Convert(string hexNumber) { int decValue = unhex_table[(byte)hexNumber[0]]; for (int i = 1; i < hexNumber.Length; i++) { decValue *= 16; decValue += unhex_table[(byte)hexNumber[i]]; } return decValue; } }
From Geekpedia: // Store integer 182 int decValue = 182; // Convert integer 182 as a hex in a string variable string hexValue = decValue.ToString("X"); // Convert the hex string back to the number int decAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
String stringrep = myintvar.ToString("X"); int num = int.Parse("FF", System.Globalization.NumberStyles.HexNumber);
If it's a really big hex string beyond the capacity of the normal integer: For .NET 3.5, we can use BouncyCastle's BigInteger class: String hex = "68c7b05d0000000002f8"; // results in "494809724602834812404472" String decimal = new Org.BouncyCastle.Math.BigInteger(hex, 16).ToString(); .NET 4.0 has the BigInteger class.
Hex to Decimal Conversion Convert.ToInt32(number, 16); Decimal to Hex Conversion int.Parse(number, System.Globalization.NumberStyles.HexNumber) For more details Check this article
Try using BigNumber in C# - Represents an arbitrarily large signed integer. Program using System.Numerics; ... var bigNumber = BigInteger.Parse("837593454735734579347547357233757342857087879423437472347757234945743"); Console.WriteLine(bigNumber.ToString("X")); Output 4F30DC39A5B10A824134D5B18EEA3707AC854EE565414ED2E498DCFDE1A15DA5FEB6074AE248458435BD417F06F674EB29A2CFECF Possible Exceptions, ArgumentNullException - value is null. FormatException - value is not in the correct format. Conclusion You can convert string and store a value in BigNumber without constraints about the size of the number unless the string is empty and non-analphabets
static string chex(byte e) // Convert a byte to a string representing that byte in hexadecimal { string r = ""; string chars = "0123456789ABCDEF"; r += chars[e >> 4]; return r += chars[e &= 0x0F]; } // Easy enough... static byte CRAZY_BYTE(string t, int i) // Take a byte, if zero return zero, else throw exception (i=0 means false, i>0 means true) { if (i == 0) return 0; throw new Exception(t); } static byte hbyte(string e) // Take 2 characters: these are hex chars, convert it to a byte { // WARNING: This code will make small children cry. Rated R. e = e.ToUpper(); // string msg = "INVALID CHARS"; // The message that will be thrown if the hex str is invalid byte[] t = new byte[] // Gets the 2 characters and puts them in seperate entries in a byte array. { // This will throw an exception if (e.Length != 2). (byte)e[CRAZY_BYTE("INVALID LENGTH", e.Length ^ 0x02)], (byte)e[0x01] }; for (byte i = 0x00; i < 0x02; i++) // Convert those [ascii] characters to [hexadecimal] characters. Error out if either character is invalid. { t[i] -= (byte)((t[i] >= 0x30) ? 0x30 : CRAZY_BYTE(msg, 0x01)); // Check for 0-9 t[i] -= (byte)((!(t[i] < 0x0A)) ? (t[i] >= 0x11 ? 0x07 : CRAZY_BYTE(msg, 0x01)) : 0x00); // Check for A-F } return t[0x01] |= t[0x00] <<= 0x04; // The moment of truth. }
This is not really easiest way but this source code enable you to right any types of octal number i.e 23.214, 23 and 0.512 and so on. Hope this will help you.. public string octal_to_decimal(string m_value) { double i, j, x = 0; Int64 main_value; int k = 0; bool pw = true, ch; int position_pt = m_value.IndexOf("."); if (position_pt == -1) { main_value = Convert.ToInt64(m_value); ch = false; } else { main_value = Convert.ToInt64(m_value.Remove(position_pt, m_value.Length - position_pt)); ch = true; } while (k <= 1) { do { i = main_value % 10; // Return Remainder i = i * Convert.ToDouble(Math.Pow(8, x)); // calculate power if (pw) x++; else x--; o_to_d = o_to_d + i; // Saving Required calculated value in main variable main_value = main_value / 10; // Dividing the main value } while (main_value >= 1); if (ch) { k++; main_value = Convert.ToInt64(Reversestring(m_value.Remove(0, position_pt + 1))); } else k = 2; pw = false; x = -1; } return (Convert.ToString(o_to_d)); }
This one worked for me: public static decimal HexToDec(string hex) { if (hex.Length % 2 == 1) hex = "0" + hex; byte[] raw = new byte[hex.Length / 2]; decimal d = 0; for (int i = 0; i < raw.Length; i++) { raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16); d += Math.Pow(256, (raw.Length - 1 - i)) * raw[i]; } return d.ToString(); return d; }
Decimal - Hexa var decValue = int.Parse(Console.ReadLine()); string hex = string.Format("{0:x}", decValue); Console.WriteLine(hex); Hexa - Decimal (use namespace: using System.Globalization;) var hexval = Console.ReadLine(); int decValue = int.Parse(hexval, NumberStyles.HexNumber); Console.WriteLine(decValue);
FOUR C# native ways to convert Hex to Dec and back: using System; namespace Hexadecimal_and_Decimal { internal class Program { private static void Main(string[] args) { string hex = "4DEAD"; int dec; // hex to dec: dec = int.Parse(hex, System.Globalization.NumberStyles.HexNumber); // or: dec = Convert.ToInt32(hex, 16); // dec to hex: hex = dec.ToString("X"); // lowcase: x, uppercase: X // or: hex = string.Format("{0:X}", dec); // lowcase: x, uppercase: X Console.WriteLine("Hexadecimal number: " + hex); Console.WriteLine("Decimal number: " + dec); } } }
My version is I think a little more understandable because my C# knowledge is not so high. I'm using this algorithm: http://easyguyevo.hubpages.com/hub/Convert-Hex-to-Decimal (The Example 2) using System; using System.Collections.Generic; static class Tool { public static string DecToHex(int x) { string result = ""; while (x != 0) { if ((x % 16) < 10) result = x % 16 + result; else { string temp = ""; switch (x % 16) { case 10: temp = "A"; break; case 11: temp = "B"; break; case 12: temp = "C"; break; case 13: temp = "D"; break; case 14: temp = "E"; break; case 15: temp = "F"; break; } result = temp + result; } x /= 16; } return result; } public static int HexToDec(string x) { int result = 0; int count = x.Length - 1; for (int i = 0; i < x.Length; i++) { int temp = 0; switch (x[i]) { case 'A': temp = 10; break; case 'B': temp = 11; break; case 'C': temp = 12; break; case 'D': temp = 13; break; case 'E': temp = 14; break; case 'F': temp = 15; break; default: temp = -48 + (int)x[i]; break; // -48 because of ASCII } result += temp * (int)(Math.Pow(16, count)); count--; } return result; } } class Program { static void Main(string[] args) { Console.Write("Enter Decimal value: "); int decNum = int.Parse(Console.ReadLine()); Console.WriteLine("Dec {0} is hex {1}", decNum, Tool.DecToHex(decNum)); Console.Write("\nEnter Hexadecimal value: "); string hexNum = Console.ReadLine().ToUpper(); Console.WriteLine("Hex {0} is dec {1}", hexNum, Tool.HexToDec(hexNum)); Console.ReadKey(); } }
Convert binary to Hex Convert.ToString(Convert.ToUInt32(binary1, 2), 16).ToUpper()
You can use this code and possible set Hex length and part's: const int decimal_places = 4; const int int_places = 4; static readonly string decimal_places_format = $"X{decimal_places}"; static readonly string int_places_format = $"X{int_places}"; public static string DecimaltoHex(decimal number) { var n = (int)Math.Truncate(number); var f = (int)Math.Truncate((number - n) * ((decimal)Math.Pow(10, decimal_places))); return $"{string.Format($"{{0:{int_places_format}}}", n)}{string.Format($"{{0:{decimal_places_format}}}", f)}"; } public static decimal HextoDecimal(string number) { var n = number.Substring(0, number.Length - decimal_places); var f = number.Substring(number.Length - decimal_places); return decimal.Parse($"{int.Parse(n, System.Globalization.NumberStyles.HexNumber)}.{int.Parse(f, System.Globalization.NumberStyles.HexNumber)}"); }
An extension method for converting a byte array into a hex representation. This pads each byte with leading zeros. /// <summary> /// Turns the byte array into its Hex representation. /// </summary> public static string ToHex(this byte[] y) { StringBuilder sb = new StringBuilder(); foreach (byte b in y) { sb.Append(b.ToString("X").PadLeft(2, "0"[0])); } return sb.ToString(); }
Here is my function: using System; using System.Collections.Generic; class HexadecimalToDecimal { static Dictionary<char, int> hexdecval = new Dictionary<char, int>{ {'0', 0}, {'1', 1}, {'2', 2}, {'3', 3}, {'4', 4}, {'5', 5}, {'6', 6}, {'7', 7}, {'8', 8}, {'9', 9}, {'a', 10}, {'b', 11}, {'c', 12}, {'d', 13}, {'e', 14}, {'f', 15}, }; static decimal HexToDec(string hex) { decimal result = 0; hex = hex.ToLower(); for (int i = 0; i < hex.Length; i++) { char valAt = hex[hex.Length - 1 - i]; result += hexdecval[valAt] * (int)Math.Pow(16, i); } return result; } static void Main() { Console.WriteLine("Enter Hexadecimal value"); string hex = Console.ReadLine().Trim(); //string hex = "29A"; Console.WriteLine("Hex {0} is dec {1}", hex, HexToDec(hex)); Console.ReadKey(); } }
My solution is a bit like back to basics, but it works without using any built-in functions to convert between number systems. public static string DecToHex(long a) { int n = 1; long b = a; while (b > 15) { b /= 16; n++; } string[] t = new string[n]; int i = 0, j = n - 1; do { if (a % 16 == 10) t[i] = "A"; else if (a % 16 == 11) t[i] = "B"; else if (a % 16 == 12) t[i] = "C"; else if (a % 16 == 13) t[i] = "D"; else if (a % 16 == 14) t[i] = "E"; else if (a % 16 == 15) t[i] = "F"; else t[i] = (a % 16).ToString(); a /= 16; i++; } while ((a * 16) > 15); string[] r = new string[n]; for (i = 0; i < n; i++) { r[i] = t[j]; j--; } string res = string.Concat(r); return res; }