Converting int to Hex in C# WinForm [duplicate] - c#

This question already has answers here:
Convert integer to hexadecimal and back again
(11 answers)
Closed 1 year ago.
So my class assignment is to make our own algorithm not using the built in functions that converts an int to hexidecimal and for the life of me it will not comply.
The example in our text converts 24032 to 0x5DE0 but what I am getting as output is 3210.
This is my code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
List<string> errorList = new List<string>();
List<int> hexList = new List<int>();
string intInput = "";
string msgOutput = "";
private void btn_Hex_Click(object sender, EventArgs e)
{
intInput = box_Int.Text;
int toHexFunc = Validator(intInput);
ToHex(toHexFunc);
}
public void ToHex(int fromHexBtn)
{
int n = fromHexBtn;
char[] hexNum = new char[100];
int i = 0;
while (n != 0)
{
int iterTemp = n % 16;
// using ASCII table from https://www.dotnetperls.com/ascii-table
if (iterTemp < 10)
{
hexNum[i] = (char)(iterTemp + 48);
i++;
}
else
{
hexNum[i] = (char)(iterTemp + 55);
i++;
}
n = n / 16;
}
for (int j = i - 1; j >= 0; j--)
{
hexList.Add(j);
}
msgOutput = String.Join("", hexList);
lbl_Message.Text = msgOutput;
}
}

base on this https://www.permadi.com/tutorial/numDecToHex/
class Program
{
static void Main(string[] args)
{
var characters = "0123456789ABCDEF";
int number = 24032;
var hexidecimal = "";
while (number > 0)
{
var remainder = number % 16;
var res = Math.Abs(number / 16);
hexidecimal = characters[remainder] + hexidecimal;
number = res;
}
hexidecimal = "0x" + hexidecimal;
WriteLine(hexadecimal);
}
}

Related

Sunday Algorithm - Index was outside the bounds of the array [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 3 years ago.
I have this Sunday Algorithm, which checks some occurrences in some text.
class Program
{
static int alphabet = 512;
static int[] table = new int[alphabet];
static int[] occurence(string pattern)
{
for(char a = (char)0; a<(char)alphabet;a++)
{
table[(int)a] = -1;
}
for(int i = 0; i< pattern.Length;i++)
{
char a = pattern[i];
table[(int)a] = i;
}
return table;
}
public static int Sunday(string text, string pattern)
{
Stopwatch timer = new Stopwatch();
timer.Start();
int k = 0;
int i = 0;
int[] table = new int[pattern.Length];
table = occurence(pattern);
while(i <= text.Length - pattern.Length)
{
int j = 0;
while(j<pattern.Length && text[i+j] == pattern[j])
{
j++;
}
if(j==pattern.Length)
{
k++;
}
i += pattern.Length;
if(i<text.Length)
{
i -= table[(int)text[i]];
}
}
timer.Stop();
Console.WriteLine(timer.Elapsed);
return k;
}
static void Main(string[] args)
{
string text = File.ReadAllText(#"C:\Users\Bacho\Desktop\Studies\Advanced Algorithms\Test Patterns\Book1.txt");
string pattern = "frankenstein";
Console.WriteLine(Sunday(text, pattern));
}
}
This is my algorithm, which works well on small input of text. In the code, I try to read a text file which consists of roughly 80 000 words and 450 000 characters. I get this exception:
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Sunday1.Program.Sunday(String text, String pattern) in C:\Users\Bacho\Desktop\Studies\Advanced Algorithms\Sunday1\Sunday1\Program.cs:line 55
at Sunday1.Program.Main(String[] args) in C:\Users\Bacho\Desktop\Studies\Advanced Algorithms\Sunday1\Sunday1\Program.cs:line 68
..at the following line:
i -= table[(int)text[i]];
Is it because it can not fit in string or is it something else?
Changing the algorithm to read and check line by line may be a solution, but is there a way to avoid it?
A char has a length of two bytes or 16 bits not 9. So I guess your alphabet should therefore probably be 65336 or simply char.MaxValue instead of 512.
Also there's no need of the static fields. You can make them local to occurence(). And in Sunday, you don't need to initialize table with new int[pattern.Length], you can directly use occurence(pattern).
class Program
{
static int[] occurence(string pattern)
{
int[] table = new int[char.MaxValue + 1];
for (int a = 0; a < char.MaxValue + 1; a++)
{
table[a] = -1;
}
for (int i = 0; i < pattern.Length; i++)
{
char a = pattern[i];
table[(int)a] = i;
}
return table;
}
public static int Sunday(string text, string pattern)
{
Stopwatch timer = new Stopwatch();
timer.Start();
int k = 0;
int i = 0;
int[] table = occurence(pattern);
while (i <= text.Length - pattern.Length)
{
int j = 0;
while (j < pattern.Length && text[i + j] == pattern[j])
{
j++;
}
if (j == pattern.Length)
{
k++;
}
i += pattern.Length;
if (i < text.Length)
{
i -= table[(int)text[i]];
}
}
timer.Stop();
Console.WriteLine(timer.Elapsed);
return k;
}
static void Main(string[] args)
{
string text = File.ReadAllText(#"C:\Users\Bacho\Desktop\Studies\Advanced Algorithms\Test Patterns\Book1.txt");
string pattern = "frankenstein";
Console.WriteLine(Sunday(text, pattern));
}
}

Make a password generator

I am currently trying to make a random password generator.
My code works fine if I only pick one type of symbols.
What's the best way to make my code to word for more than one type?
Also what parameters would you add to make the password more secured?
I am thinking of adding an if loop to check if there are more than two same letters, symbols or numbers in a row.
That's how my interface looks like:
and that is my code:
public partial class Form1 : Form
{
// Max number of identical characters in a row
const int Maximum_Identical = 2;
// lower case chars
const string lower_chars = "abcdefghijklmnopqrstuvwxyz";
// capital chars
const string capital_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// numbers
const string numbers = "0123456789";
// symbols
const string symbols = #"!#$%&*#\";
// password lenght
int lenght;
private void button1_Click(object sender, EventArgs e)
{
//use stringbuilder so I can add more chars later
StringBuilder password = new StringBuilder();
//take max lenght from numericUpDown
lenght = Convert.ToInt32(numericUpDown1.Value);
// random instance so I can use Next and don't get loops
Random rdm = new Random();
if (small_letters__Box.Checked)
{
//add a random small character to pass untill it reaches the selected lenght
while (lenght-- > 0 )
{
password.Append(lower_chars[rdm.Next(lower_chars.Length)]);
}
}
if (capital_letters__Box.Checked)
{
//add a random capital character to pass untill it reaches the selected lenght
while (lenght-- > 0)
{
password.Append(capital_chars[rdm.Next(capital_chars.Length)]);
}
}
if (numbers_Box.Checked)
{
//add a random character to pass untill it reaches the selected lenght
while (lenght-- > 0)
{
password.Append(numbers[rdm.Next(numbers.Length)]);
}
}
if (symbols_Box.Checked)
{
//add a random character to pass untill it reaches the selected lenght
while (lenght-- > 0)
{
password.Append(symbols[rdm.Next(symbols.Length)]);
}
}
textBox1.Text = password.ToString();
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
}
}
Your password generation has 2 steps.
Determine the character set
Create a password randomly from the character set of length n
Function 1 creates the character set:
// Make sure you have using System.Linq;
private List<char> GetCharacterSet()
{
IEnumerable<char> returnSet = new char[]{};
if (small_letters__Box.Checked)
{
returnSet = returnSet.Append(lower_chars);
}
if (capital_letters__Box.Checked)
{
returnSet = returnSet.Append(capital_chars);
}
if (numbers_Box.Checked)
{
returnSet = returnSet.Append(numbers);
}
if (symbols_Box.Checked)
{
returnSet = returnSet.Append(symbols);
}
return returnSet.ToList();
}
Function 2 creates a password of given length from your character set
private string GetPassword(int length, List<char> characterSet)
{
if(characterSet.Count < 1)
{
throw new ArgumentException("characterSet contains no items!");
}
if(length < 1)
{
return "";
}
Random rdm = new Random();
StringBuilder password = new StringBuilder();
for(int i = 0; i < length; i++){
int charIndex = rdm.Next(0, characterSet.Count)
password.Append(characterSet[charIndex]);
}
return password.ToString();
}
Then simply rig your button click event handler to call these functions and display the resulting password.
below code is my already written code which I wrote more than a couple of years ago and I still use it in my many of my projects where needed, it covers all you are in need of
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading;
public static class ArrayExtentions
{
public static object[] Shuffle(this object[] array)
{
var alreadySwaped = new HashSet<Tuple<int, int>>();
var rndLoopCount = RandomUtils.GetRandom(Convert.ToInt32(array.Length / 4), Convert.ToInt32((array.Length / 2) + 1));
for (var i = 0; i <= rndLoopCount; i++)
{
int rndIndex1 = 0, rndIndex2 = 0;
do
{
rndIndex1 = RandomUtils.GetRandom(0, array.Length);
rndIndex2 = RandomUtils.GetRandom(0, array.Length);
} while (alreadySwaped.Contains(new Tuple<int, int>(rndIndex1, rndIndex2)));
alreadySwaped.Add(new Tuple<int, int>(rndIndex1, rndIndex2));
var swappingItem = array[rndIndex1];
array[rndIndex1] = array[rndIndex2];
array[rndIndex2] = swappingItem;
}
return array;
}
}
public class RandomUtils
{
private static readonly ThreadLocal<Random> RndLocal = new ThreadLocal<Random>(() => new Random(GetUniqueSeed()));
private static int GetUniqueSeed()
{
long next, current;
var guid = Guid.NewGuid().ToByteArray();
var seed = BitConverter.ToInt64(guid, 0);
do
{
current = Interlocked.Read(ref seed);
next = current * BitConverter.ToInt64(guid, 3);
} while (Interlocked.CompareExchange(ref seed, next, current) != current);
return (int)next ^ Environment.TickCount;
}
public static int GetRandom(int min, int max)
{
Contract.Assert(max >= min);
return RndLocal.Value.Next(min, max);
}
public static int GetRandom(int max)
{
return RndLocal.Value.Next(max);
}
public static double GetRandom()
{
return RndLocal.Value.NextDouble();
}
}
public class StringUtility
{
private const string UpperAlpha = "ABCDEFGHIJKLMNOPQRSTUWXYZ";
private const string LowerAlpha = "abcdefghijklmnopqrstuwxyz";
private const string Numbers = "0123456789";
private const string SpecialChars = "~!##$%^&*()_-+=.?";
private static string CreateSourceString(bool includeLowerCase, bool includeUpperCase, bool includenumbers, bool includeSpChars)
{
Contract.Assert(includeLowerCase || includeUpperCase || includenumbers || includeSpChars);
var sb = new StringBuilder();
if (includeLowerCase) sb.Append(LowerAlpha);
if (includeUpperCase) sb.Append(UpperAlpha);
if (includenumbers) sb.Append(Numbers);
if (includeSpChars) sb.Append(SpecialChars);
return sb.ToString();
}
private static string GenerateString(string sourceString, int length = 6)
{
var rndString = Shuffle(sourceString);
var builder = new StringBuilder();
for (var i = 0; i < length; i++)
builder.Append(rndString[RandomUtils.GetRandom(0, rndString.Length)]);
return builder.ToString();
}
public static string GenerateRandomString(int length = 6,
bool includenumbers = false,
bool includeSpChars = false)
{
var sourceStr = CreateSourceString(true, true, includenumbers, includeSpChars);
return GenerateString(sourceStr, length);
}
public static string GenerateRandomString(int minLength,
int maxLength,
bool includenumbers = false,
bool includeSpChars = false)
{
if (maxLength < minLength) maxLength = minLength;
var len = RandomUtils.GetRandom(minLength, maxLength + 1);
return GenerateRandomString(len, includenumbers, includeSpChars);
}
public static string Shuffle(string str)
{
var alreadySwaped = new HashSet<Tuple<int, int>>();
var rndLoopCount = RandomUtils.GetRandom(Convert.ToInt32(str.Length / 4), Convert.ToInt32((str.Length / 2) + 1));
var strArray = str.ToArray();
for (var i = 0; i <= rndLoopCount; i++)
{
int rndIndex1 = 0, rndIndex2 = 0;
do
{
rndIndex1 = RandomUtils.GetRandom(0, str.Length);
rndIndex2 = RandomUtils.GetRandom(0, str.Length);
} while (alreadySwaped.Contains(new Tuple<int, int>(rndIndex1, rndIndex2)));
alreadySwaped.Add(new Tuple<int, int>(rndIndex1, rndIndex2));
var swappingChar = strArray[rndIndex1];
strArray[rndIndex1] = strArray[rndIndex2];
strArray[rndIndex2] = swappingChar;
}
return new string(strArray);
}
public static string GeneratePassword(PasswordComplexity complexityLevel)
{
switch (complexityLevel)
{
case PasswordComplexity.Simple: return GenerateSimplePassword();
case PasswordComplexity.Medium: return GenerateMediumPassword();
case PasswordComplexity.Strong: return GenerateStrongPassword();
case PasswordComplexity.Stronger: return GenerateStrongerPassword();
}
return null;
}
private static string GenerateSimplePassword()
{
return GenerateRandomString(6, 9);
}
private static string GenerateMediumPassword()
{
var passLen = RandomUtils.GetRandom(6, 10);
var numCount = RandomUtils.GetRandom(1, 3);
var alphaStr = GenerateRandomString(passLen - numCount);
var numStr = GenerateString(Numbers, numCount);
var pass = alphaStr + numStr;
return Shuffle(pass);
}
private static string GenerateStrongPassword()
{
var lowerCharCount = RandomUtils.GetRandom(2, 5);
var upperCharCount = RandomUtils.GetRandom(2, 5);
var numCount = RandomUtils.GetRandom(2, 4);
var spCharCount = RandomUtils.GetRandom(2, 4);
var lowerAlphaStr = GenerateString(LowerAlpha, lowerCharCount);
var upperAlphaStr = GenerateString(UpperAlpha, upperCharCount);
var spCharStr = GenerateString(SpecialChars, spCharCount);
var numStr = GenerateString(Numbers, numCount);
var pass = lowerAlphaStr + upperAlphaStr + spCharStr + numStr;
return Shuffle(pass);
}
private static string GenerateStrongerPassword()
{
var lowerCharCount = RandomUtils.GetRandom(5, 12);
var upperCharCount = RandomUtils.GetRandom(4, 8);
var numCount = RandomUtils.GetRandom(4, 6);
var spCharCount = RandomUtils.GetRandom(4, 6);
var lowerAlphaStr = GenerateString(LowerAlpha, lowerCharCount);
var upperAlphaStr = GenerateString(UpperAlpha, upperCharCount);
var spCharStr = GenerateString(SpecialChars, spCharCount);
var numStr = GenerateString(Numbers, numCount);
var pass = lowerAlphaStr + upperAlphaStr + spCharStr + numStr;
return Shuffle(Shuffle(pass));
}
public enum PasswordComplexity
{
Simple, Medium, Strong, Stronger
}
}
I write this code for you. You can just copy and use it. All of my code is just a method that you can pass appropriate arguments and it gives you back a completely randomized password. I test it several times before answering your question, It works well.
private string GeneratePassword(bool useCapitalLetters, bool useSmallLetters, bool useNumbers, bool useSymbols, int passLenght)
{
Random random = new Random();
StringBuilder password = new StringBuilder(string.Empty);
//This for loop is for selecting password chars in order
for (int i = 0;;)
{
if (useCapitalLetters)
{
password.Append((char)random.Next(65, 91)); //Capital letters
++i; if (i >= passLenght) break;
}
if (useSmallLetters)
{
password.Append((char)random.Next(97, 122)); //Small letters
++i; if (i >= passLenght) break;
}
if (useNumbers)
{
password.Append((char)random.Next(48, 57)); //Number letters
++i; if (i >= passLenght) break;
}
if (useSymbols)
{
password.Append((char)random.Next(35, 38)); //Symbol letters
++i; if (i >= passLenght) break;
}
}
//This for loop is for disordering password characters
for (int i = 0; i < password.Length; ++i)
{
int randomIndex1 = random.Next(password.Length);
int randomIndex2 = random.Next(password.Length);
char temp = password[randomIndex1];
password[randomIndex1] = password[randomIndex2];
password[randomIndex2] = temp;
}
return password.ToString();
}
an answer with complete randomize char and using the max repeat of char, i have added a shuffle string function:
const int Maximum_Identical = 2; // Max number of identical characters in a row
const string lower_chars = "abcdefghijklmnopqrstuvwxyz"; // lower case chars
const string capital_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //capital chars
const string numbers = "0123456789"; //numbers
const string symbols = #"!#$%&*#\"; //symbols
int lenght = 6; //
bool lowercase = true, capital=true, num=true, sym=true;
List<char[]> PasswordSet = new List<char[]>();
List<char[]> charSet = new List<char[]>();
List<int[]> countSet = new List<int[]>();
if (lowercase) charSet.Add(lower_chars.ToArray());
if (capital) charSet.Add(capital_chars.ToArray());
if (num) charSet.Add(numbers.ToArray());
if (sym) charSet.Add(symbols.ToArray());
foreach(var c in charSet)
countSet.Add(new int[c.Length]);
Random rdm = new Random();
//we create alist with each type with a length char (max repeat char included)
for(int i = 0; i < charSet.Count;i++)
{
var lng = 1;
var p0 = "";
while (true)
{
var ind = rdm.Next(0, charSet[i].Length);
if (countSet[i][ind] < Maximum_Identical )
{
countSet[i][ind] += 1;
lng++;
p0 += charSet[i][ind];
}
if (lng == lenght) break;
}
PasswordSet.Add(p0.ToArray());
}
//generate a password with the desired length with at less one char in desired type,
//and we choose randomly in desired type to complete the length of password
var password = "";
for(int i = 0; i < lenght; i++)
{
char p;
if (i < PasswordSet.Count)
{
int id;
do
{
id = rdm.Next(0, PasswordSet[i].Length);
p = PasswordSet[i][id];
} while (p == '\0');
password += p;
PasswordSet[i][id] = '\0';
}
else
{
int id0;
int id1;
do
{
id0 = rdm.Next(0, PasswordSet.Count);
id1 = rdm.Next(0, PasswordSet[id0].Length);
p = PasswordSet[id0][id1];
} while (p == '\0');
password += p;
PasswordSet[id0][id1] = '\0';
}
}
//you could shuffle the final password
password = Shuffle.StringMixer(password);
shuffle string function:
static class Shuffle
{
static System.Random rnd = new System.Random();
static void Fisher_Yates(int[] array)
{
int arraysize = array.Length;
int random;
int temp;
for (int i = 0; i < arraysize; i++)
{
random = i + (int)(rnd.NextDouble() * (arraysize - i));
temp = array[random];
array[random] = array[i];
array[i] = temp;
}
}
public static string StringMixer(string s)
{
string output = "";
int arraysize = s.Length;
int[] randomArray = new int[arraysize];
for (int i = 0; i < arraysize; i++)
{
randomArray[i] = i;
}
Fisher_Yates(randomArray);
for (int i = 0; i < arraysize; i++)
{
output += s[randomArray[i]];
}
return output;
}
}
There you go :
string[] charList =
{
"abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"0123456789",
"#\"!#$%&*#\\"
};
int desiredPasswordLength = 12;
var randomNumberGenerator = new Random();
string generatedPassword = "";
for (int i = randomNumberGenerator.Next() % 4; desiredPasswordLength > 0; i = (i+1) % 4)
{
var takeRandomChars = randomNumberGenerator.Next() % 3;
for (int j = 0; j < takeRandomChars; j++)
{
var randomChar = randomNumberGenerator.Next() % charList[i].Length;
char selectedChar = charList[i][randomChar % charList[i].Length];
generatedPassword = string.Join("", generatedPassword, selectedChar);
}
desiredPasswordLength -= takeRandomChars;
}
Console.WriteLine("Generated password: {0}",generatedPassword);
private static string GeneratorPassword(UInt16 length = 8)
{
const string chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
Random rnd = new Random();
System.Threading.Thread.Sleep(2);
for (int i = 0; i < length; i++)
{
int index = 0;
if (i % 3 == 0)
{
index = rnd.Next(0, 10);
}
else if (i % 3 == 1)
{
index = rnd.Next(10, 36);
}
else
{
index = rnd.Next(36, 62);
}
sb.Insert(rnd.Next(0, sb.Length), chars[index].ToString());
}
return sb.ToString();
}
static void Main(string[] args)
{
for (int j= 0; j < 100; j++)
{
Console.WriteLine( GeneratorPassword());
}
Console.ReadLine();
}

i want to generate alfa numeric otp in asp.net c#

public void generate()
{
string alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string small_alphabets = "abcdefghijklmnopqrstuvwxyz";
string numbers = "1234567890";
string characters = numbers;
characters += alphabets + small_alphabets + numbers;
int length =6;
string opt = string.Empty;
for (int i = 0; i < length; i++)
{
string character = string.Empty;
do
{
int index = new Random().Next(0, characters.Length);
character = characters.ToCharArray()[index].ToString();
} while (otp.IndexOf(character) != -1);
otp += character;
}
string str= otp;
}
This is my code, which is not working for me.
I want to try small alphabet, capital alphabet and 0 to 9 number combination.
Here is the code :
var chars1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
var stringChars1 = new char[6];
var random1 = new Random();
for (int i = 0; i < stringChars1.Length; i++)
{
stringChars1[i] = chars1[random1.Next(chars1.Length)];
}
var str= new String(stringChars1);
This code will give you numeric otp of n digits.
public static int GenerateOTP(int digits)
{
if (digits < 3)
return new Random().Next(10, 99);
else
return new Random().Next(MultiplyNTimes(digits), MultiplyNTimes(digits + 1) - 1);
}
private static int MultiplyNTimes(int n)
{
if (n == 1)
return 1;
else
return 10 * MultiplyNTimes(n - 1);
}

SQF to C# - Encryption code convertion

G'Day. I am attempting to convert a function that was initially made for Bohemia Interactives language SQF to C#. The script is designed to encrypt a string with the encryption method RC4, however, it works a little bit different to the way this is traditionally done thanks to limitations of the arma3 engine. The whole idea of this is so I can encrypt a string with the C# program, and decrypt it through Arma 3 in-game.
Here is the code I am trying to convert from.
/*
Function: ALiVE_fnc_crypt
Author(s): Naught
Version: 1.0
Description:
Encrypts or decrypts a string with a specified encryption key.
Parameters:
0 - Decrypt (0) or encrypt (1) [number]
1 - Encryption method name [string]
2 - Encrypted or plain data [string]
3 - Encryption key [string]
Returns:
Encrypted or decrypted data or nothing on failure [string:nil]
Note(s):
1. Current encryption method names:
- "rc4" // Rivest Cipher 4 Stream Encryption Algorithm
*/
// Constants
MAX_CHAR_SIZE = 8;
CHAR_ZERO_REP = 256;
private ["_method", "_key"];
_encText = _this select 0;
_key = _this select 1;
private ["_fnc_intToBin"];
_fnc_intToBin = {
private ["_int", "_bin", "_pwr", "_bool"];
_int = _this select 0;
_bin = if ((count _this) > 1) then {_this select 1} else {[]};
for "_i" from (MAX_CHAR_SIZE - 1) to 0 step (-1) do
{
_pwr = 2^(_i);
_bool = _pwr <= _int;
_bin set [(count _bin), _bool];
if (_bool) then {_int = _int - _pwr};
};
_bin
};
private ["_bin"];
_bin = [];
// Convert string to UTF-8 binary
{ // count (faster than forEach)
[(if (_x == CHAR_ZERO_REP) then {0} else {_x}), _bin] call _fnc_intToBin;
false;
} count toArray(_encText);
systemChat str _bin;
// Encrypt & decrypt methods
_key = toArray(_key);
private ["_keyLen", "_state", "_temp", "_j"];
_keyLen = count _key;
_state = [];
_temp = 0;
_j = 0;
// Key-Scheduling Algorithm
for "_i" from 0 to 255 do {_state set [_i,_i]};
for "_i" from 0 to 255 do
{
_temp = _state select _i;
_j = (_j + _temp + (_key select (_i mod _keyLen))) mod 256;
_state set [_i, (_state select _j)];
_state set [_j, _temp];
};
private ["_temp1", "_temp2", "_rand", "_i", "_mod", "_rbit"];
_temp1 = 0;
_temp2 = 0;
_rand = [];
_i = 0;
_j = 0;
hint str _bin;
// Pseudo-Random Generation Algorithm
{
_mod = _forEachIndex % MAX_CHAR_SIZE;
if (_mod == 0) then
{
_i = (_i + 1) mod 256;
_j = (_j + (_state select _i)) mod 256;
_temp1 = _state select _i;
_temp2 = _state select _j;
_state set [_i, _temp2];
_state set [_j, _temp1];
_rand = [(_state select ((_temp1 + _temp2) mod 256))] call _fnc_intToBin;
};
_rbit = _rand select _mod;
_bin set [_forEachIndex, (_x && !_rbit) || {!_x && _rbit}]; // XOR
} forEach _bin;
private ["_dec", "_buf", "_mod"];
_dec = 0;
_buf = [];
// Convert binary array to UTF-8 string
{
_mod = _forEachIndex % MAX_CHAR_SIZE;
if (_x) then {_dec = _dec + 2^((MAX_CHAR_SIZE - 1) - _mod)};
if (_mod == 7) then
{
if (_dec == 0) then {_dec = CHAR_ZERO_REP};
_buf set [(count _buf), _dec];
_dec = 0;
};
} forEach _bin;
toString(_buf)
I have made slight adjustments to this code, and it all still works fine in Arma 3.
Now, the converted function. I have changed about everything in this code from what my initial code was to try and get it working, so at this point, it may be completely incorrect, however, I will include it anyway.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace encrypt
{
class Program
{
static public int MAX_CHAR_SIZE = 8;
static public int CHAR_ZERO_REP = 256;
static public int _keyLen;
static void Main()
{
string[] args = new string[2];
args[0] = "Some Random Code";
args[1] = "4tuIc9tai";
string text = args[0];
// Convert the text to an array of decimal unicode || Same as toArray in arma 3
string[] txtArray = new string[text.Length];
txtArray = text.ToCharArray().Select(c => c.ToString()).ToArray();
int[] utf = getUni(txtArray);
// Convert the key to an array of decimal unicode || Same as toArray in arma 3
string[] keyArray = new string[args[1].Length];
keyArray = args[1].ToCharArray().Select(c => c.ToString()).ToArray();
int[] key = getUni(keyArray);
// Debug the output
//foreach (int i in utf){Console.Write(i); Console.Write(",");} Console.WriteLine();foreach (int i in key){Console.Write(i);Console.Write(","); }
// Convert string to UTF-8 binary
Dictionary<int, bool> _bin = new Dictionary<int, bool>();
foreach (int i in utf)
{
int _num;
if (i == CHAR_ZERO_REP)
{
_num = 0;
}
else
{
_num = i;
}
_bin = intToBin(_num, _bin);
}
foreach (KeyValuePair<int, bool> i in _bin)
{
Console.Write(Convert.ToString(i.Value));
Console.Write(", ");
}
// Encrypt & decrypt methods
_keyLen = key.Length;
int[] _state = new int[1024];
int _temp = 0;
int _j = 0;
// Key-Scheduling Algorithm
for (int _i = 0; _i < 255; _i++)
{
_state.SetValue(_i, _i);
}
for (int _i = 0; _i < 255; _i++)
{
_temp = _state[_i];
_j = (_j + _temp + key[_i % _keyLen]) % 256;
_state.SetValue(_i, _state[_j]);
_state.SetValue(_j, _temp);
}
// Pseudo-Random Generation Algorithm
int _temp1 = 0;
int _temp2 = 0;
Dictionary<int, bool> _rand = new Dictionary<int, bool>();
int __i = 0;
int __j = 0;
int indx = 0;
for (int i = 0; i < _bin.Count-1; i++)
{
int _mod = indx % MAX_CHAR_SIZE;
if (_mod == 0)
{
__i = (__i + 1) % 256;
__j = (__j + _state[__i]) % 256;
_temp1 = _state[__i];
_temp2 = _state[__j];
_state.SetValue(__i, _temp2);
_state.SetValue(__j, _temp1);
_rand = intToBin(_state[_temp1 + _temp2] % 256, _rand);
}
bool _rbit = _rand[_mod];
bool _bit = _bin[i];
if (_bin.ContainsKey(indx))
{
_bin.Remove(indx);
}
_bin.Add(indx, (_bit && !_rbit) || (!_bit && _rbit));
indx++;
}
// Convert binary array to UTF-8 string
int _dec = 0;
int[] _buf = new int[_bin.Count];
for (int i = 0; i < _bin.Count-1; i++)
{
int _mod = i % MAX_CHAR_SIZE;
Console.WriteLine(i);
if (_bin[i])
{
_dec = _dec + 2 ^ ((MAX_CHAR_SIZE - 1) - _mod);
}
if (_mod == 7)
{
if (_dec == 0)
{
_dec = CHAR_ZERO_REP;
}
_buf.SetValue(_dec, _buf.Length-1);
_dec = 0;
}
_buf.SetValue(_dec, _buf.Length - 1);
}
Console.ReadLine();
}
static int[] getUni(string[] txtArray)
{
int[] ret = new int[txtArray.Length];
int idx = 0;
foreach (string i in txtArray)
{
ret.SetValue(Encoding.UTF8.GetBytes(i)[0], idx);
idx++;
}
return ret;
}
static Dictionary<int, bool> intToBin(int val, Dictionary<int, bool> bin)
{
for (int i = MAX_CHAR_SIZE-1; i > 0; i--)
{
int _pwr = 2 ^ i;
bool _bool = _pwr <= val;
int cc = bin.Count;
if (bin.ContainsKey(cc))
{
bin.Remove(cc);
}
bin.Add(cc, _bool);
if (_bool)
{
val = val - _pwr;
}
}
return bin;
}
}
}
Any help what so ever would be great :)

Removing Leading Zeros in a Char Array

I'm attempting to subtract two strings (of theoretically infinite length) without the use of libraries like BigIntbut I was wondering if anybody has any good ideas on how to remove the leading zeros in the corner cases like the one below?
static void Main(string[] args)
{
Console.WriteLine(Subtract("10", "10005"));
}
static string ReverseInput(string inputString)
{
char[] charArray = inputString.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
static string Subtract(string firstNumInput, string secondNumInput)
{
string firstNum = String.Empty;
string secondNum = String.Empty;
bool negative = false;
// Reverse order of string input
if (firstNumInput.Length > secondNumInput.Length)
{
firstNum = ReverseInput(firstNumInput);
secondNum = ReverseInput(secondNumInput);
}
else if (firstNumInput.Length < secondNumInput.Length)
{
negative = true;
firstNum = ReverseInput(secondNumInput);
secondNum = ReverseInput(firstNumInput);
}
else if (firstNumInput.Length == secondNumInput.Length)
{
// iterate through string to find largest
}
char[] result = new char[firstNum.Length + 1];
int resultLength = 0;
int carry = 0;
for (int i = 0; i < firstNum.Length; i++)
{
int an = (i < firstNum.Length) ? int.Parse(firstNum[i].ToString()) : 0;
int bn = (i < secondNum.Length) ? int.Parse(secondNum[i].ToString()) : 0;
int rn = an - bn - carry;
if (rn < 0)
{
carry = 1;
rn += 10;
}
else
{
carry = 0;
}
result[resultLength++] = (char)(rn + '0');
}
// create the result string from the char array
string finalResult = ReverseInput(new string(result, 0, resultLength));
if (negative)
{
finalResult = '-' + finalResult;
}
return finalResult;
}
Are you looking for TrimStart?
// create the result string from the char array
string finalResult = ReverseInput(new string(result, 0, resultLength)).TrimStart('0');

Categories