String to Hex int array? - c#

Is it possible to convert a HEX string to an integer array?
// This string...
string a = "8FCC44";
// Should look like this:
int[] b = {0x8f,0xcc,0x44};
But I don't have any idea how to do this.
I found this question, but i can't understand the answer. I am new to C#, so it would be nice if anybody could give me an example.
Thanks in advance!

int[] ConvertToIntArray(string a)
{
List<int> x = new List<int>();
for(int i=0; i<a.Length-1; i+=2)
x.Add(int.Parse(a.Substring(i, 2), System.Globalization.NumberStyles.HexNumber));
return x.ToArray();
}
You can then print them as Hex or Decimal using ToString() overloads of int (Int32) class.

Another way:
var a = "8fcc44";
var b = Enumerable.Range(0, a.Length / 2).Select(x =>
Convert.ToInt32(a.Substring(x * 2, 2), 16)).ToArray();

The answer focuses on Java, but it is also possible to do this in C# in a similar way. Basicly you have to divide the string into substrings, each 2 characters long:
"8FCC44" -> "8F", "CC", "44"
You can do this using a for loop:
for (int i = 0; i < a.Length; i += 2)
The loop variable i represents the start index of the current substring, this is why it always increases by 2. We can convert each substring using Int32.Parse:
Convert.ToInt32(a.Substring(i, 2), 16);
The last parameter represents the base of the source string (HEX = base 16).
Now we need an array to store the results. The size of the array can be calculated by the length of the string, divided by the length of each substring (= 2):
int[] b = new int[a.Length / 2];
To bring it all together your code could look like this:
string a = "8FCC44";
int[] b = new int[a.Length / 2];
for (int i = 0, int j = 0; i < a.Length; i += 2, j++)
b[j] = Convert.ToInt32(a.Substring(i, 2), 16);
Hope this helps!

static void Main(string[] args)
{
string a = "8fcc44";
int itemNumber = 0;
int[] iArray = new int[3];
for (int i = 0; i < a.Length - 1; i += 2)
{
iArray[itemNumber] = (int.Parse(a.Substring(i, 2), System.Globalization.NumberStyles.HexNumber));
itemNumber++;
}
}

Related

Simple cycle and wrong element

Here`s some code:
foreach (int[] temp in intList)
{
string str = GenerateGamma(0,1,10,temp);
if (str == "924890128")
answer.Add(temp);
}
Where in intList there are int arrays and each one of them has the following property: array[1] = 1(length of array is 10). Well, when I looked in answer, then I saw the array 1 4 6 0 9 3 2 7 5 8, so array[1] = 4.
Here is code of GenerateGamma().
public static string GenerateGamma(int i0, int j0, int m, int[] b)
{
Constants ct = new Constants();
int[] gamma = new int[9];
int[] inside_array = b;
string result = "";
int temp_i = i0, temp_j = j0, inttemp = 0;
for (int t = 1; t <= 9; t++)
{
temp_i = ((temp_i + 1) % m);
temp_j = ((temp_j + inside_array[temp_i]) % m);
inttemp = inside_array[temp_i];
inside_array[temp_i] = inside_array[temp_j];
inside_array[temp_j] = inttemp;
gamma[t-1] = (inside_array[(inside_array[temp_i]+inside_array[temp_j])%m]%m);
}
result = string.Join("",gamma);
return result;
}
Arrays are reference types, if you change passed array inside GenerateGamma() method the original array will be changed too.
Your array is changed because inside method you have:
int[] inside_array = b;
Here you don't create a copy of passed array, you just create copy of reference to array. So, you have one array and two references (b and inside_array) which point to the same array: b[0] = 1; and inside_array[0] = 1; do the same - they modify the same array.
If you want copy:
int[] inside_array = new int[b.Length];
for (int a = 0; a < inside_array.Length; a++)
{
inside_array[a] = b[a];
}
After this you will have two arrays and when you change one array another one won't be changed.

The biggest value in array and check if all elements in array have equal values. (C#)

I'm working on a project. The user inputs a value(n) and that value is multiplied by 2. Then the user inputs the exact same times a new number (n*2). So I have to figure out if every couple of numbers are equal and if not to print the biggest difference between one of the couples. In order to do that I need Biggest value in an array and somehow to check if all elements in an array are equal. I'm new to C# and I don't know much about arrays.(btw sorry about the use of language, I'm foreigner)
I came up with this code so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EqualPairs
{
class Program
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
int sum = 0;
int diff = 0;
int[] sumAll = new int[n];
int[] differ = new int[n];
for (int i = 1; i <= n; i++)
{
sum = 0;
diff = 0;
for (int j = 1; j <= 2; j++)
{
int number = int.Parse(Console.ReadLine());
sum = sum + number;
diff = Math.Abs(diff - number);
}
sumAll[i - 1] = sum;
differ[i - 1] = diff;
}
}
}
}
I'm not sure exactly what you're trying to do with your program, but to answer your questions:
Find max value in an array:
int maxValue = yourArray.Max();
Check if all values in your array are equal (using System.Linq):
int first = yourArray.First();
bool allElementsEqual = yourArray.All(x => x == first);
Edit based on OP's comment:
If I were you, I'd create an intermediate array couplesArray. Not sure how you're planning to set up your inputs and all that, but I'm assuming yourArray has an even number of values. I don't know how you're defining max difference and all that, so perhaps drop some of my Math.Abs() calls:
int[] yourArray = { 1, 2, 0, 3, 4, -1};
int[] couplesArray = new int[yourArray.Count() / 2];
for (int i = 0; i < couplesArray.Length; i++)
{
couplesArray[i] = yourArray[2 * i] + yourArray[2 * i + 1];
}
int first = couplesArray.First();
bool allElementsEqual = couplesArray.All(x => x == first);
int maxDifference = Math.Max(Math.Abs(couplesArray.Max()), Math.Abs(couplesArray.Min()));
string outputString = allElementsEqual ? "Equal" : maxDifference.ToString();
Console.WriteLine(outputString);

How to perform combinatoric task in C#

i have a problem with an combinatoric task. I want to have a code which can handle this math calculation 48/5 = 1712304 (5! = 5*4*3*2*1 = 120 48*47*46*45*44 = 205476480 205476480/120 = 1712304)
Here some more details.
I have a string array with 48 strings. The strings have a length between 2 and 3 chars.
string array[] = new string[]{"A1","1D","410" /*[....]*/}
i want to combine 5 strings together, and i want to do this with the whole array, my biggest problem is that a combined string is just allowed to include each of the 48 strings just once. And each combined string have to be unique.
In the end i need a List with 1712304 string entries, which have to be between 10 and 15 degits long. For example one string could look like this "A11A4103E1T".
Back to the math, i know that there are 1712304 combined options so any other result must be wrong. That's where my problem appears.
I created the following code without succesful result
string[] siDigit = new string[iNumDigits];
List<string> liste = new List<string>();
const int iDigitBase = 48;
const int iNumDigits = 5;
for (int i = 0; i < 1712303; ++i)
{
int i2 = i;
for (int i3 = 0; i3 < iNumDigits; ++i3)
{
siDigit[i3] = array[i2 % iDigitBase];
i2 /= iDigitBase;
}
bool duplicate_free = siDigit.Distinct().Count() == siDigit.Length;
if (duplicate_free == true)
{
liste.Add(siDigit[0] + siDigit[1] + siDigit[2] + siDigit[3] + siDigit[4]);
Console.Write(siDigit[0] + siDigit[1] + siDigit[2] + siDigit[3] + siDigit[4]);
Console.WriteLine();
}
}
What i get is way to less entries in my list, i just get 1317051 entries and dont know why. I cant find any solution for my problem, may someone out there can help me out.
Any help would be greatly appreciated.
P.S In germany they dont teach better english :)
I think your algorithm is wrong.
Consider i equals 0, i2 equals 0, so siDigit[i3](i3 = 0, 1, 2, 3 ,4) are array[0], duplicate_free is false. You lose one. So, you can not get all entries.
Here is a recursive algorithm:
private static void GetCombination(ref List<string[]> list, string[] t, int n, int m, int[] b, int M)
{
for (int i = n; i >= m; i--)
{
b[m - 1] = i - 1;
if (m > 1)
{
GetCombination(ref list, t, i - 1, m - 1, b, M);
}
else
{
if (list == null)
{
list = new List<string[]>();
}
string[] temp = new string[M];
for (int j = 0; j < b.Length; j++)
{
temp[j] = t[b[j]];
}
list.Add(temp);
}
}
}
public static List<string[]> GetCombination(string[] t, int n)
{
if (t.Length < n)
{
return null;
}
int[] temp = new int[n];
List<string[]> list = new List<string[]>();
GetCombination(ref list, t, t.Length, n, temp, n);
return list;
}

Rotate a char array

What are alternatives to this method
tmp = c[0];
c[0] = c[1];
c[1] = c[2];
c[2] = c[3];
c[3] = tmp;
to left rotate a char array with 4 elements
Using generics and rotating in place (thanks Jon Skeet for the suggestion):
static void Rotate<T>(T[] source)
{
var temp = source[0];
Array.Copy(source, 1, source, 0, source.Length - 1);
source[source.Length - 1] = temp;
}
These should work for any array of at least 2 length, and on any array.
If performance is critical and the arrays are always small, use this:
static void Rotate<T>(T[] source)
{
var temp = source[0];
for (int i = 0; i < source.Length - 1; i++)
source[i] = source[i + 1];
source[source.Length - 1] = temp;
}
The first method is the fastest with large arrays, but for 4 items, this one's almost as fast as your example method.
An alterantive to rotating the array, is to rotate the index when accessing the array, i.e you are creating a virtual ring
int origin = someValue;
int x = c[(i + origin) % c.Length];
I'm not sure if you're asking for a more efficient method or for an easier way to type that, but i'm going to try answering you assuming you want an easier way
so try:
int temp = c[0]
for(int i = 0; i < c.count; i++)
{
if (i == (c.count - 1))
{
c[i] = temp;
break;
}
c[i] = c[i + 1];
}
Do the job in single step.
Using System.Linq;
int[] ar = { 1,2,3,4,5};
int k = 1; //
int[] ar1= ar.Skip(k) // Start with the last elements
.Concat(ar.Take(k)) // Then the first elements
.ToArray();
Output-- 2,3,4,5,1
In ruby rotating array can be done in one line.
def array_rotate(arr)
i, j = arr.length - 1, 0
arr[j],arr[i], i, j = arr[i], arr[j], i - 1, j + 1 while(j<arr.length/2)
puts "#{arr}"
end

need a better way add leading digits to int and return array of digits

I need to create a modulus check which adds leading digits, lets say 0, to a seed int. I then need to return an array of digits in the array as I need to do a calculation on each digit to return a new whole number.
my code is as follows,
var seed = 1234;
var seedString = seed.ToString();
var test = new List<int>();
for(int i = 0; i < 10 - seedString.Length; i++)
{
test.Add(0);
}
var value = seed;
for(int i = 0; i < seedString.Length; i ++)
{
test.Insert(10 - seedString.Length, value % 10);
value = value / 10;
}
is there an easier way of doing this?
If you want to convert your number to a 10-digit string, you can format the number using a Custom Numeric Format String as follows:
string result = seed.ToString("0000000000");
// result == "0000001234"
See: The "0" Custom Specifier
If you need a 10-element array consisting of the individual digits, try this:
int[] result = new int[10];
for (int value = seed, i = result.Length; value != 0; value /= 10)
{
result[--i] = value % 10;
}
// result == new int[] { 0, 0, 0, 0, 0, 0, 1, 2, 3, 4 }
See also: Fastest way to separate the digits of an int into an array in .NET?
Try this:
int myNumber = 1234;
string myStringNumber = myNumber.ToString().PadLeft(10, '0');
HTH
Another shorthand way of getting the string representation would be
int num = 1234;
num.ToString("D10");

Categories

Resources