Hexadecimal Loops in C# - c#

My goal was to get a 3DES password and for that im missing the last 6 digits.
for (int i = 0; i <= 16777215; i++)
{
string hexValue = i.ToString("X").PadLeft(6, '0');
}

You could just get the maximum number in your set of hexadecimals which goes from [0,FFFFFF] in decimal the set goes from [0, 16777215]
for(int i = 0; i <= 16777215; i++) {
string hexValue = i.ToString("X");
// your logic goes here...
}

This should do it:
var allHexadecimals = Enumerable.Range(0, 0xFFFFFF + 1)
.Select(i => i.ToString("X").PadLeft(6, '0'));

You can actually convert directly to Hex from c#, check out this article:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/how-to-convert-between-hexadecimal-strings-and-numeric-types
e.g. for(int i = 0x0; i < 0xff;i+=0x01) {Console.WriteLine(iConsole.WriteLine(value.ToString("X"));}

Related

Find all possible combinations of word with and without hyphens

For a string that may have zero or more hyphens in it, I need to extract all the different possibilities with and without hyphens.
For example, the string "A-B" would result in "A-B" and "AB" (two possibilities).
The string "A-B-C" would result in "A-B-C", "AB-C", "A-BC" and "ABC" (four possibilities).
The string "A-B-C-D" would result in "A-B-C-D", "AB-C-D", "A-BC-D", "A-B-CD", "AB-CD", "ABC-D", "A-BCD" and "ABCD" (eight possibilities).
...etc, etc.
I've experimented with some nested loops but haven't been able to get anywhere near the desired result. I suspect I need something recursive unless there is some simple solution I am overlooking.
NB. This is to build a SQL query (shame that SQL Server does't have MySQL's REGEXP pattern matching).
Here is one attempt I was working on. This might work if I do this recursively.
string keyword = "A-B-C-D";
List<int> hyphens = new List<int>();
int pos = keyword.IndexOf('-');
while (pos != -1)
{
hyphens.Add(pos);
pos = keyword.IndexOf('-', pos + 1);
}
for (int i = 0; i < hyphens.Count(); i++)
{
string result = keyword.Substring(0, hyphens[i]) + keyword.Substring(hyphens[i] + 1);
Response.Write("<p>" + result);
}
A B C D are words of varying length.
Take a look at your sample cases. Have you noticed a pattern?
With 1 hyphen there are 2 possibilities.
With 2 hyphens there are 4 possibilities.
With 3 hyphens there are 8 possibilities.
The number of possibilities is 2n.
This is literally exponential growth, so if there are too many hyphens in the string, it will quickly become infeasible to print them all. (With just 30 hyphens there are over a billion combinations!)
That said, for smaller numbers of hyphens it might be interesting to generate a list. To do this, you can think of each hyphen as a bit in a binary number. If the bit is 1, the hyphen is present, otherwise it is not. So this suggests a fairly straightforward solution:
Split the original string on the hyphens
Let n = the number of hyphens
Count from 2n - 1 down to 0. Treat this counter as a bitmask.
For each count begin building a string starting with the first part.
Concatenate each of the remaining parts to the string in order, preceded by a hyphen only if the corresponding bit in the bitmask is set.
Add the resulting string to the output and continue until the counter is exhausted.
Translated to code we have:
public static IEnumerable<string> EnumerateHyphenatedStrings(string s)
{
string[] parts = s.Split('-');
int n = parts.Length - 1;
if (n > 30) throw new Exception("too many hyphens");
for (int m = (1 << n) - 1; m >= 0; m--)
{
StringBuilder sb = new StringBuilder(parts[0]);
for (int i = 1; i <= n; i++)
{
if ((m & (1 << (i - 1))) > 0) sb.Append('-');
sb.Append(parts[i]);
}
yield return sb.ToString();
}
}
Fiddle: https://dotnetfiddle.net/ne3N8f
You should be able to track each hyphen position, and basically say its either there or not there. Loop through all the combinations, and you got all your strings. I found the easiest way to track it was using a binary, since its easy to add those with Convert.ToInt32
I came up with this:
string keyword = "A-B-C-D";
string[] keywordSplit = keyword.Split('-');
int combinations = Convert.ToInt32(Math.Pow(2.0, keywordSplit.Length - 1.0));
List<string> results = new List<string>();
for (int j = 0; j < combinations; j++)
{
string result = "";
string hyphenAdded = Convert.ToString(j, 2).PadLeft(keywordSplit.Length - 1, '0');
// Generate string
for (int i = 0; i < keywordSplit.Length; i++)
{
result += keywordSplit[i] +
((i < keywordSplit.Length - 1) && (hyphenAdded[i].Equals('1')) ? "-" : "");
}
results.Add(result);
}
This works for me:
Func<IEnumerable<string>, IEnumerable<string>> expand = null;
expand = xs =>
{
if (xs != null && xs.Any())
{
var head = xs.First();
if (xs.Skip(1).Any())
{
return expand(xs.Skip(1)).SelectMany(tail => new []
{
head + tail,
head + "-" + tail
});
}
else
{
return new [] { head };
}
}
else
{
return Enumerable.Empty<string>();
}
};
var keyword = "A-B-C-D";
var parts = keyword.Split('-');
var results = expand(parts);
I get:
ABCD
A-BCD
AB-CD
A-B-CD
ABC-D
A-BC-D
AB-C-D
A-B-C-D
I've tested this code and it is working as specified in the question. I stored the strings in a List<string>.
string str = "AB-C-D-EF-G-HI";
string[] splitted = str.Split('-');
List<string> finalList = new List<string>();
string temp = "";
for (int i = 0; i < splitted.Length; i++)
{
temp += splitted[i];
}
finalList.Add(temp);
temp = "";
for (int diff = 0; diff < splitted.Length-1; diff++)
{
for (int start = 1, limit = start + diff; limit < splitted.Length; start++, limit++)
{
int i = 0;
while (i < start)
{
temp += splitted[i++];
}
while (i <= limit)
{
temp += "-";
temp += splitted[i++];
}
while (i < splitted.Length)
{
temp += splitted[i++];
}
finalList.Add(temp);
temp = "";
}
}
I'm not sure your question is entirely well defined (i.e. could you have something like A-BCD-EF-G-H?). For "fully" hyphenated strings (A-B-C-D-...-Z), something like this should do:
string toParse = "A-B-C-D";
char[] toParseChars = toPase.toCharArray();
string result = "";
string binary;
for(int i = 0; i < (int)Math.pow(2, toParse.Length/2); i++) { // Number of subsets of an n-elt set is 2^n
binary = Convert.ToString(i, 2);
while (binary.Length < toParse.Length/2) {
binary = "0" + binary;
}
char[] binChars = binary.ToCharArray();
for (int k = 0; k < binChars.Length; k++) {
result += toParseChars[k*2].ToString();
if (binChars[k] == '1') {
result += "-";
}
}
result += toParseChars[toParseChars.Length-1];
Console.WriteLine(result);
}
The idea here is that we want to create a binary word for each possible hyphen. So, if we have A-B-C-D (three hyphens), we create binary words 000, 001, 010, 011, 100, 101, 110, and 111. Note that if we have n hyphens, we need 2^n binary words.
Then each word maps to the output you desire by inserting the hyphen where we have a '1' in our word (000 -> ABCD, 001 -> ABC-D, 010 -> AB-CD, etc). I didn't test the code above, but this is at least one way to solve the problem for fully hyphenated words.
Disclaimer: I didn't actually test the code

Get number inside of a string and do a loop

I want to get a number of a string, and separate the string and the number, and then, do a loop and call a method the number of times the string says.
The string has to have this structure: "ABJ3" (Only one number accepted and 3 characters before it)
This is my code, but it repeat hundred of times, I don't know why
int veces = 0;
for (int i = 0; i < m.Length; i++)
{
if (Char.IsDigit(m[i]))
veces = Convert.ToInt32(m[i]);
}
if (m.Length == 4)
{
for (int i = 0; i <= veces; i++)
{
m = m.Substring(0, 3);
operaciones(m, u, t);
Thread.Sleep(100);
}
}
operaciones(m,u,t);
if (u.Length >= 14)
{
u = u.Substring(0, 15);
}
Some help please?
You have to convert your m[i] ToString() right now you are sending the char value to Convert.ToInt32 and that is a much higher value (9 = 57 for example)
char t = '9';
int te = Convert.ToInt32(t.ToString());
Console.WriteLine(te);
This gives us a result of 9 but
char t = '9';
int te = Convert.ToInt32(t);
Console.WriteLine(te);
Gives us a result of 57
So you need to change
veces = Convert.ToInt32(m[i]);
to
veces = Convert.ToInt32(m[i].ToString());
Hope it helped.
Best regards //KH.
You cannot convert the digits like this. You're overwriting them and taking only the last one. Moreover, you're taking its ASCII code, not digit value. You have to extract all digits first then convert them:
int position = 0;
int veces = 0;
string temp = ""
for (int i = 0; i < m.Length; i++) {
if (Char.IsDigit(m[i]))
position = i;
else
break;
}
veces = Convert.ToInt32(m.SubString(0, i + 1));
Alternatively, you can use regex instead.

Create a new String with Duplicate Letters

I am trying to create a string that inserts a duplicate letter from the original into the modified. For example, the output of one run would be:
Original word:
stack
Output:
sstack, sttack, staack, stacck, stackk
Does that make sense? I have this so far, and I feel i am close, but I am suing the wrong method to reassemble the string. Any help would be appreciated:
// Use ToCharArray to convert string to array.
char[] array = originalWord.ToCharArray();
// Loop through array.
for (int i = 0; i < array.Length; i++)
{
// Get character from array.
char letter = array[i];
string result = array.ToString();
string result2 = string.Join("", result.Select(x => x + letter));
Console.Write(result2);
}
This should work:
var original = "stack";
for (int i = 0; i < original.Length; i++)
Console.WriteLine(original.Insert(i, original[i].ToString()));
You can use String.Insert to insert a string at a given index into another string.
IEnumerable<string> strings = originalWord
.Select((c, idx) => originalWord.Insert(idx, c.ToString()));
Fixed :
string originalWord = "stack";
// Use ToCharArray to convert string to array.
char[] array = originalWord.ToCharArray();
// Loop through array.
for (int i = 0; i < array.Length; i++)
{
// Get character from array.
char letter = array[i];
string result = originalWord.Insert(i, letter.ToString(CultureInfo.InvariantCulture));
Console.WriteLine(result);
}
The Linq way :
IEnumerable<string> words = originalWord.Select((letter, i) => originalWord.Insert(i, letter.ToString(CultureInfo.InvariantCulture)));
You can use String.Insert() method like;
string s = "stack";
for (int i = 0; i < s.Length; i++)
{
Console.WriteLine (s.Insert(i, s[i].ToString()));
}
Here is a DEMO.
Oh god, already aded 3 answers when I writing it. Damn..

C# : Split a sequence of numbers after given parameter length

I have a number something like this :
12345668788451223356456898941220036696897894
Now, the question is how can I split the number after each 8 digits.That is,
I need the output as :
12345668
78845122 and so on up to the end of the number.
If I convert it to string, I don't have a method so that I could split it only with length parameter.
Thanks in advance for answering.
String approach
If I convert it to string, I don't have a method so that I could split it only with length parameter.
Well you have Substring, don't you? You could use LINQ:
var numbers = Enumerable.Range(0, bigNumber.Length / 8)
.Select(x => bigNumber.Substring(x * 8, 8)
.ToList();
or a straight loop:
var numbers = new List<string>();
for (int i = 0; i < bigNumber.Length / 8; i++)
{
numbers.Add(bigNumber.Substring(i * 8, 8);
}
If you need to end up with a List<int> instead, just add a call to int.Parse in there.
(You should check that the input string length is a multiple of 8 first.)
BigInteger approach
It's not clear what form you have this number in to start with. If it's a BigInteger, you could keep using DivRem:
BigInteger value = ...;
List<BigInteger> results = new List<BigInteger>();
BigInteger divisor = 100000000L;
for (int i = 0; i < count; i++)
{
BigInteger tmp;
value = BigInteger.DivRem(value, divisor, out tmp);
results.Add(tmp);
}
Note that I'm using count here rather than just looping until value is 0, in case you have lots of leading 0s. You need to know how many numbers you're trying to extract :)
Use this regex to split after each 8 digits,
\d{1,8}
OR
(\d{1,8})
Output:
12345668
78845122
33564568
98941220
03669689
7894
Have you tried using
string string.substring(int startIndex,int length)
In you case, you can write a loop to extract the 8 digits from the string till all the numbers are extracted
string sDigits = "12345668788451223356456898941220036696897894";
int iArrLen = sDigits.length / 8;
string[] sArrDigitList = new string[iArrLen];
for(int i=0; i < sDigits.length; i++)
{
sArrDigitList[i] = sDigits.substring(0, 8);
sDigits = sDigits.substring(sDigits.length-8);
}

How to get the maximum number of a particular length

I have a number, for example 1234567897865; how do I max it out and create 99999999999999 ?
I did this this way:
int len = ItemNo.ToString().Length;
String maxNumString = "";
for (int i = 0; i < len; i++)
{
maxNumString += "9";
}
long maxNumber = long.Parse(maxNumString);
what would be the better, proper and shorter way to approach this task?
var x = 1234567897865;
return Math.Pow(10, Math.Ceiling(Math.Log10(x+1e-6))) - 1;
To expand on comments below, if this problem was expressed in hex or binary, it could be done very simply using shift operators
i.e., "I have a number, in hex,, for example 3A67FD5C; how do I max it out and create FFFFFFFF?"
I'd have to play with this to make sure it works exactly, but it would be something like this:
var x = 0x3A67FD5C;
var p = 0;
while((x=x>>1)>0) p++; // count how many binary values are in the number
return (1L << 4*(1+p/4)) - 1; // using left shift, generate 2 to
// that power and subtract one
long maxNumber = long.Parse(new String('9', ItemNo.ToString().Length));
Try this:
int v = 1;
do {
v = v * 10;
} while (v <= number);
return v - 1;
int numDigits = (int)Math.Ceiling(Math.Log10(number));
int result = (int)(Math.Pow(10, numDigits) - 1)
I don't have a compiler available at the moment, so some additional string/double conversions may need to happen here.

Categories

Resources