C# code to vba code for decryption - c#

I need assistance or someone that can point me in the right direction
I have Acces Vba code that does a custom encryption and i need to rewrite this code for a c# application
I have already done all of the code conversions but the results are not the same
I think it could be the encoding standard but I'm not sure
Edit
I cant use any extra libraries it must all be native C#
(I know of the vb Library)
C#
internal class Class1
{
public string fEncryptString(string TheString, int nbrPlaces)
{
//string sEnc = "91tephen#S", expected = "œ˜:²84²7 ©";
int i, intlength;
double mult, tmp;
string tmpst = "";
intlength = TheString.Length;
nbrPlaces = (nbrPlaces % 8);
mult = Math.Pow(2, nbrPlaces);
for (i = 1; i < intlength + 1; i++)
{
tmp = Convert.ToChar(Mid(TheString, i, 1));
tmp = tmp * mult;
tmp = tmp % 256 + tmp / 256;
tmp = Math.Floor(tmp);
int x = Convert.ToInt16(tmp);
tmpst = tmpst + Encoding.Default.GetString(new byte[] { Convert.ToByte(x) });
}
return tmpst;
}
public string Mid(string s, int a, int b)
{
string temp = s.Substring(a - 1, b);
return temp;
}
public string Encrypt(string strString)
{
//Scramble the order of characters
int intLen;
string strRtt = "";
//Determine length of string
intLen = strString.Length;
//Assign first two characters
strRtt = strString.Substring(strString.Length - 1) + strString.Substring(strString.Length - 2, 1);
//Assign all other characters except the last character
for (int i = 2; i < intLen - 1; i++)
{
strRtt += Mid(strString, i, 1);
}
//Assign the last character
strRtt = strRtt + strString.Substring(1, 1);
//Encrypt the scrambled string
return fEncryptString(strRtt, 7);
}
}
VBA
Public Function fEncryptString(TheString As String, ByVal nbrPlaces As Byte) As String
Dim tmp As Integer, i As Integer, mult As Integer
Dim intLength As Integer, tmpSt As String
intLength = Len(TheString)
tmpSt = ""
nbrPlaces = nbrPlaces Mod 8 'no point doing more than 7, besides
mult = 2 ^ nbrPlaces 'mult (an Integer) would be too small
For i = 1 To intLength
tmp = Asc(Mid$(TheString, i, 1)) 'get the ASCII value of each character
tmp = tmp * mult 'apply the multiplier
tmp = tmp Mod 256 + tmp \ 256 'rotate any 'carry' bit
tmpSt = tmpSt & Chr$(tmp) 'add the character to the String
Next i
fEncryptString = tmpSt
End Function
Public Function fEncrypt(strString As String)
'Scramble the order of characters
Dim intLen As Integer
Dim strRtt As String
'Determine length of string
intLen = Len(strString)
'Assign first two characters
strRtt = Right(strString, 1) & Left(Right(strString, 2), 1)
'Assign all other characters except the last character
For i = 2 To intLen - 2
strRtt = strRtt & Mid(strString, i, 1)
Next i
'Assign the last character
strRtt = strRtt & Left(strString, 1)
'Encrypt the scrambled string
fEncrypt = fEncryptString(strRtt, 7)
End Function

Related

Generate (pseudo-) base-26 number representation (similar to Excel column names) [duplicate]

How do you convert a numerical number to an Excel column name in C# without using automation getting the value directly from Excel.
Excel 2007 has a possible range of 1 to 16384, which is the number of columns that it supports. The resulting values should be in the form of excel column names, e.g. A, AA, AAA etc.
Here's how I do it:
private string GetExcelColumnName(int columnNumber)
{
string columnName = "";
while (columnNumber > 0)
{
int modulo = (columnNumber - 1) % 26;
columnName = Convert.ToChar('A' + modulo) + columnName;
columnNumber = (columnNumber - modulo) / 26;
}
return columnName;
}
If anyone needs to do this in Excel without VBA, here is a way:
=SUBSTITUTE(ADDRESS(1;colNum;4);"1";"")
where colNum is the column number
And in VBA:
Function GetColumnName(colNum As Integer) As String
Dim d As Integer
Dim m As Integer
Dim name As String
d = colNum
name = ""
Do While (d > 0)
m = (d - 1) Mod 26
name = Chr(65 + m) + name
d = Int((d - m) / 26)
Loop
GetColumnName = name
End Function
Sorry, this is Python instead of C#, but at least the results are correct:
def ColIdxToXlName(idx):
if idx < 1:
raise ValueError("Index is too small")
result = ""
while True:
if idx > 26:
idx, r = divmod(idx - 1, 26)
result = chr(r + ord('A')) + result
else:
return chr(idx + ord('A') - 1) + result
for i in xrange(1, 1024):
print "%4d : %s" % (i, ColIdxToXlName(i))
You might need conversion both ways, e.g from Excel column adress like AAZ to integer and from any integer to Excel. The two methods below will do just that. Assumes 1 based indexing, first element in your "arrays" are element number 1.
No limits on size here, so you can use adresses like ERROR and that would be column number 2613824 ...
public static string ColumnAdress(int col)
{
if (col <= 26) {
return Convert.ToChar(col + 64).ToString();
}
int div = col / 26;
int mod = col % 26;
if (mod == 0) {mod = 26;div--;}
return ColumnAdress(div) + ColumnAdress(mod);
}
public static int ColumnNumber(string colAdress)
{
int[] digits = new int[colAdress.Length];
for (int i = 0; i < colAdress.Length; ++i)
{
digits[i] = Convert.ToInt32(colAdress[i]) - 64;
}
int mul=1;int res=0;
for (int pos = digits.Length - 1; pos >= 0; --pos)
{
res += digits[pos] * mul;
mul *= 26;
}
return res;
}
I discovered an error in my first post, so I decided to sit down and do the the math. What I found is that the number system used to identify Excel columns is not a base 26 system, as another person posted. Consider the following in base 10. You can also do this with the letters of the alphabet.
Space:.........................S1, S2, S3 : S1, S2, S3
....................................0, 00, 000 :.. A, AA, AAA
....................................1, 01, 001 :.. B, AB, AAB
.................................... …, …, … :.. …, …, …
....................................9, 99, 999 :.. Z, ZZ, ZZZ
Total states in space: 10, 100, 1000 : 26, 676, 17576
Total States:...............1110................18278
Excel numbers columns in the individual alphabetical spaces using base 26. You can see that in general, the state space progression is a, a^2, a^3, … for some base a, and the total number of states is a + a^2 + a^3 + … .
Suppose you want to find the total number of states A in the first N spaces. The formula for doing so is A = (a)(a^N - 1 )/(a-1). This is important because we need to find the space N that corresponds to our index K. If I want to find out where K lies in the number system I need to replace A with K and solve for N. The solution is N = log{base a} (A (a-1)/a +1). If I use the example of a = 10 and K = 192, I know that N = 2.23804… . This tells me that K lies at the beginning of the third space since it is a little greater than two.
The next step is to find exactly how far in the current space we are. To find this, subtract from K the A generated using the floor of N. In this example, the floor of N is two. So, A = (10)(10^2 – 1)/(10-1) = 110, as is expected when you combine the states of the first two spaces. This needs to be subtracted from K because these first 110 states would have already been accounted for in the first two spaces. This leaves us with 82 states. So, in this number system, the representation of 192 in base 10 is 082.
The C# code using a base index of zero is
private string ExcelColumnIndexToName(int Index)
{
string range = string.Empty;
if (Index < 0 ) return range;
int a = 26;
int x = (int)Math.Floor(Math.Log((Index) * (a - 1) / a + 1, a));
Index -= (int)(Math.Pow(a, x) - 1) * a / (a - 1);
for (int i = x+1; Index + i > 0; i--)
{
range = ((char)(65 + Index % a)).ToString() + range;
Index /= a;
}
return range;
}
//Old Post
A zero-based solution in C#.
private string ExcelColumnIndexToName(int Index)
{
string range = "";
if (Index < 0 ) return range;
for(int i=1;Index + i > 0;i=0)
{
range = ((char)(65 + Index % 26)).ToString() + range;
Index /= 26;
}
if (range.Length > 1) range = ((char)((int)range[0] - 1)).ToString() + range.Substring(1);
return range;
}
This answer is in javaScript:
function getCharFromNumber(columnNumber){
var dividend = columnNumber;
var columnName = "";
var modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnName = String.fromCharCode(65 + modulo).toString() + columnName;
dividend = parseInt((dividend - modulo) / 26);
}
return columnName;
}
Easy with recursion.
public static string GetStandardExcelColumnName(int columnNumberOneBased)
{
int baseValue = Convert.ToInt32('A');
int columnNumberZeroBased = columnNumberOneBased - 1;
string ret = "";
if (columnNumberOneBased > 26)
{
ret = GetStandardExcelColumnName(columnNumberZeroBased / 26) ;
}
return ret + Convert.ToChar(baseValue + (columnNumberZeroBased % 26) );
}
I'm surprised all of the solutions so far contain either iteration or recursion.
Here's my solution that runs in constant time (no loops). This solution works for all possible Excel columns and checks that the input can be turned into an Excel column. Possible columns are in the range [A, XFD] or [1, 16384]. (This is dependent on your version of Excel)
private static string Turn(uint col)
{
if (col < 1 || col > 16384) //Excel columns are one-based (one = 'A')
throw new ArgumentException("col must be >= 1 and <= 16384");
if (col <= 26) //one character
return ((char)(col + 'A' - 1)).ToString();
else if (col <= 702) //two characters
{
char firstChar = (char)((int)((col - 1) / 26) + 'A' - 1);
char secondChar = (char)(col % 26 + 'A' - 1);
if (secondChar == '#') //Excel is one-based, but modulo operations are zero-based
secondChar = 'Z'; //convert one-based to zero-based
return string.Format("{0}{1}", firstChar, secondChar);
}
else //three characters
{
char firstChar = (char)((int)((col - 1) / 702) + 'A' - 1);
char secondChar = (char)((col - 1) / 26 % 26 + 'A' - 1);
char thirdChar = (char)(col % 26 + 'A' - 1);
if (thirdChar == '#') //Excel is one-based, but modulo operations are zero-based
thirdChar = 'Z'; //convert one-based to zero-based
return string.Format("{0}{1}{2}", firstChar, secondChar, thirdChar);
}
}
Same implementation in Java
public String getExcelColumnName (int columnNumber)
{
int dividend = columnNumber;
int i;
String columnName = "";
int modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
i = 65 + modulo;
columnName = new Character((char)i).toString() + columnName;
dividend = (int)((dividend - modulo) / 26);
}
return columnName;
}
int nCol = 127;
string sChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string sCol = "";
while (nCol >= 26)
{
int nChar = nCol % 26;
nCol = (nCol - nChar) / 26;
// You could do some trick with using nChar as offset from 'A', but I am lazy to do it right now.
sCol = sChars[nChar] + sCol;
}
sCol = sChars[nCol] + sCol;
Update: Peter's comment is right. That's what I get for writing code in the browser. :-) My solution was not compiling, it was missing the left-most letter and it was building the string in reverse order - all now fixed.
Bugs aside, the algorithm is basically converting a number from base 10 to base 26.
Update 2: Joel Coehoorn is right - the code above will return AB for 27. If it was real base 26 number, AA would be equal to A and the next number after Z would be BA.
int nCol = 127;
string sChars = "0ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string sCol = "";
while (nCol > 26)
{
int nChar = nCol % 26;
if (nChar == 0)
nChar = 26;
nCol = (nCol - nChar) / 26;
sCol = sChars[nChar] + sCol;
}
if (nCol != 0)
sCol = sChars[nCol] + sCol;
..And converted to php:
function GetExcelColumnName($columnNumber) {
$columnName = '';
while ($columnNumber > 0) {
$modulo = ($columnNumber - 1) % 26;
$columnName = chr(65 + $modulo) . $columnName;
$columnNumber = (int)(($columnNumber - $modulo) / 26);
}
return $columnName;
}
Just throwing in a simple two-line C# implementation using recursion, because all the answers here seem far more complicated than necessary.
/// <summary>
/// Gets the column letter(s) corresponding to the given column number.
/// </summary>
/// <param name="column">The one-based column index. Must be greater than zero.</param>
/// <returns>The desired column letter, or an empty string if the column number was invalid.</returns>
public static string GetColumnLetter(int column) {
if (column < 1) return String.Empty;
return GetColumnLetter((column - 1) / 26) + (char)('A' + (column - 1) % 26);
}
Although there are already a bunch of valid answers1, none get into the theory behind it.
Excel column names are bijective base-26 representations of their number. This is quite different than an ordinary base 26 (there is no leading zero), and I really recommend reading the Wikipedia entry to grasp the differences. For example, the decimal value 702 (decomposed in 26*26 + 26) is represented in "ordinary" base 26 by 110 (i.e. 1x26^2 + 1x26^1 + 0x26^0) and in bijective base-26 by ZZ (i.e. 26x26^1 + 26x26^0).
Differences aside, bijective numeration is a positional notation, and as such we can perform conversions using an iterative (or recursive) algorithm which on each iteration finds the digit of the next position (similarly to an ordinary base conversion algorithm).
The general formula to get the digit at the last position (the one indexed 0) of the bijective base-k representation of a decimal number m is (f being the ceiling function minus 1):
m - (f(m / k) * k)
The digit at the next position (i.e. the one indexed 1) is found by applying the same formula to the result of f(m / k). We know that for the last digit (i.e. the one with the highest index) f(m / k) is 0.
This forms the basis for an iteration that finds each successive digit in bijective base-k of a decimal number. In pseudo-code it would look like this (digit() maps a decimal integer to its representation in the bijective base -- e.g. digit(1) would return A in bijective base-26):
fun conv(m)
q = f(m / k)
a = m - (q * k)
if (q == 0)
return digit(a)
else
return conv(q) + digit(a);
So we can translate this to C#2 to get a generic3 "conversion to bijective base-k" ToBijective() routine:
class BijectiveNumeration {
private int baseK;
private Func<int, char> getDigit;
public BijectiveNumeration(int baseK, Func<int, char> getDigit) {
this.baseK = baseK;
this.getDigit = getDigit;
}
public string ToBijective(double decimalValue) {
double q = f(decimalValue / baseK);
double a = decimalValue - (q * baseK);
return ((q > 0) ? ToBijective(q) : "") + getDigit((int)a);
}
private static double f(double i) {
return (Math.Ceiling(i) - 1);
}
}
Now for conversion to bijective base-26 (our "Excel column name" use case):
static void Main(string[] args)
{
BijectiveNumeration bijBase26 = new BijectiveNumeration(
26,
(value) => Convert.ToChar('A' + (value - 1))
);
Console.WriteLine(bijBase26.ToBijective(1)); // prints "A"
Console.WriteLine(bijBase26.ToBijective(26)); // prints "Z"
Console.WriteLine(bijBase26.ToBijective(27)); // prints "AA"
Console.WriteLine(bijBase26.ToBijective(702)); // prints "ZZ"
Console.WriteLine(bijBase26.ToBijective(16384)); // prints "XFD"
}
Excel's maximum column index is 16384 / XFD, but this code will convert any positive number.
As an added bonus, we can now easily convert to any bijective base. For example for bijective base-10:
static void Main(string[] args)
{
BijectiveNumeration bijBase10 = new BijectiveNumeration(
10,
(value) => value < 10 ? Convert.ToChar('0'+value) : 'A'
);
Console.WriteLine(bijBase10.ToBijective(1)); // prints "1"
Console.WriteLine(bijBase10.ToBijective(10)); // prints "A"
Console.WriteLine(bijBase10.ToBijective(123)); // prints "123"
Console.WriteLine(bijBase10.ToBijective(20)); // prints "1A"
Console.WriteLine(bijBase10.ToBijective(100)); // prints "9A"
Console.WriteLine(bijBase10.ToBijective(101)); // prints "A1"
Console.WriteLine(bijBase10.ToBijective(2010)); // prints "19AA"
}
1 This generic answer can eventually be reduced to the other, correct, specific answers, but I find it hard to fully grasp the logic of the solutions without the formal theory behind bijective numeration in general. It also proves its correctness nicely. Additionally, several similar questions link back to this one, some being language-agnostic or more generic. That's why I thought the addition of this answer was warranted, and that this question was a good place to put it.
2 C# disclaimer: I implemented an example in C# because this is what is asked here, but I have never learned nor used the language. I have verified it does compile and run, but please adapt it to fit the language best practices / general conventions, if necessary.
3 This example only aims to be correct and understandable ; it could and should be optimized would performance matter (e.g. with tail-recursion -- but that seems to require trampolining in C#), and made safer (e.g. by validating parameters).
I wanted to throw in my static class I use, for interoping between col index and col Label. I use a modified accepted answer for my ColumnLabel Method
public static class Extensions
{
public static string ColumnLabel(this int col)
{
var dividend = col;
var columnLabel = string.Empty;
int modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnLabel = Convert.ToChar(65 + modulo).ToString() + columnLabel;
dividend = (int)((dividend - modulo) / 26);
}
return columnLabel;
}
public static int ColumnIndex(this string colLabel)
{
// "AD" (1 * 26^1) + (4 * 26^0) ...
var colIndex = 0;
for(int ind = 0, pow = colLabel.Count()-1; ind < colLabel.Count(); ++ind, --pow)
{
var cVal = Convert.ToInt32(colLabel[ind]) - 64; //col A is index 1
colIndex += cVal * ((int)Math.Pow(26, pow));
}
return colIndex;
}
}
Use this like...
30.ColumnLabel(); // "AD"
"AD".ColumnIndex(); // 30
private String getColumn(int c) {
String s = "";
do {
s = (char)('A' + (c % 26)) + s;
c /= 26;
} while (c-- > 0);
return s;
}
Its not exactly base 26, there is no 0 in the system. If there was, 'Z' would be followed by 'BA' not by 'AA'.
if you just want it for a cell formula without code, here's a formula for it:
IF(COLUMN()>=26,CHAR(ROUND(COLUMN()/26,1)+64)&CHAR(MOD(COLUMN(),26)+64),CHAR(COLUMN()+64))
In Delphi (Pascal):
function GetExcelColumnName(columnNumber: integer): string;
var
dividend, modulo: integer;
begin
Result := '';
dividend := columnNumber;
while dividend > 0 do begin
modulo := (dividend - 1) mod 26;
Result := Chr(65 + modulo) + Result;
dividend := (dividend - modulo) div 26;
end;
end;
A little late to the game, but here's the code I use (in C#):
private static readonly string _Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static int ColumnNameParse(string value)
{
// assumes value.Length is [1,3]
// assumes value is uppercase
var digits = value.PadLeft(3).Select(x => _Alphabet.IndexOf(x));
return digits.Aggregate(0, (current, index) => (current * 26) + (index + 1));
}
In perl, for an input of 1 (A), 27 (AA), etc.
sub excel_colname {
my ($idx) = #_; # one-based column number
--$idx; # zero-based column index
my $name = "";
while ($idx >= 0) {
$name .= chr(ord("A") + ($idx % 26));
$idx = int($idx / 26) - 1;
}
return scalar reverse $name;
}
Though I am late to the game, Graham's answer is far from being optimal. Particularly, you don't have to use the modulo, call ToString() and apply (int) cast. Considering that in most cases in C# world you would start numbering from 0, here is my revision:
public static string GetColumnName(int index) // zero-based
{
const byte BASE = 'Z' - 'A' + 1;
string name = String.Empty;
do
{
name = Convert.ToChar('A' + index % BASE) + name;
index = index / BASE - 1;
}
while (index >= 0);
return name;
}
More than 30 solutions already, but here's my one-line C# solution...
public string IntToExcelColumn(int i)
{
return ((i<16926? "" : ((char)((((i/26)-1)%26)+65)).ToString()) + (i<2730? "" : ((char)((((i/26)-1)%26)+65)).ToString()) + (i<26? "" : ((char)((((i/26)-1)%26)+65)).ToString()) + ((char)((i%26)+65)));
}
After looking at all the supplied Versions here, I decided to do one myself, using recursion.
Here is my vb.net Version:
Function CL(ByVal x As Integer) As String
If x >= 1 And x <= 26 Then
CL = Chr(x + 64)
Else
CL = CL((x - x Mod 26) / 26) & Chr((x Mod 26) + 1 + 64)
End If
End Function
Refining the original solution (in C#):
public static class ExcelHelper
{
private static Dictionary<UInt16, String> l_DictionaryOfColumns;
public static ExcelHelper() {
l_DictionaryOfColumns = new Dictionary<ushort, string>(256);
}
public static String GetExcelColumnName(UInt16 l_Column)
{
UInt16 l_ColumnCopy = l_Column;
String l_Chars = "0ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String l_rVal = "";
UInt16 l_Char;
if (l_DictionaryOfColumns.ContainsKey(l_Column) == true)
{
l_rVal = l_DictionaryOfColumns[l_Column];
}
else
{
while (l_ColumnCopy > 26)
{
l_Char = l_ColumnCopy % 26;
if (l_Char == 0)
l_Char = 26;
l_ColumnCopy = (l_ColumnCopy - l_Char) / 26;
l_rVal = l_Chars[l_Char] + l_rVal;
}
if (l_ColumnCopy != 0)
l_rVal = l_Chars[l_ColumnCopy] + l_rVal;
l_DictionaryOfColumns.ContainsKey(l_Column) = l_rVal;
}
return l_rVal;
}
}
Here is an Actionscript version:
private var columnNumbers:Array = ['A', 'B', 'C', 'D', 'E', 'F' , 'G', 'H', 'I', 'J', 'K' ,'L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
private function getExcelColumnName(columnNumber:int) : String{
var dividend:int = columnNumber;
var columnName:String = "";
var modulo:int;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnName = columnNumbers[modulo] + columnName;
dividend = int((dividend - modulo) / 26);
}
return columnName;
}
JavaScript Solution
/**
* Calculate the column letter abbreviation from a 1 based index
* #param {Number} value
* #returns {string}
*/
getColumnFromIndex = function (value) {
var base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
var remainder, result = "";
do {
remainder = value % 26;
result = base[(remainder || 26) - 1] + result;
value = Math.floor(value / 26);
} while (value > 0);
return result;
};
These my codes to convert specific number (index start from 1) to Excel Column.
public static string NumberToExcelColumn(uint number)
{
uint originalNumber = number;
uint numChars = 1;
while (Math.Pow(26, numChars) < number)
{
numChars++;
if (Math.Pow(26, numChars) + 26 >= number)
{
break;
}
}
string toRet = "";
uint lastValue = 0;
do
{
number -= lastValue;
double powerVal = Math.Pow(26, numChars - 1);
byte thisCharIdx = (byte)Math.Truncate((columnNumber - 1) / powerVal);
lastValue = (int)powerVal * thisCharIdx;
if (numChars - 2 >= 0)
{
double powerVal_next = Math.Pow(26, numChars - 2);
byte thisCharIdx_next = (byte)Math.Truncate((columnNumber - lastValue - 1) / powerVal_next);
int lastValue_next = (int)Math.Pow(26, numChars - 2) * thisCharIdx_next;
if (thisCharIdx_next == 0 && lastValue_next == 0 && powerVal_next == 26)
{
thisCharIdx--;
lastValue = (int)powerVal * thisCharIdx;
}
}
toRet += (char)((byte)'A' + thisCharIdx + ((numChars > 1) ? -1 : 0));
numChars--;
} while (numChars > 0);
return toRet;
}
My Unit Test:
[TestMethod]
public void Test()
{
Assert.AreEqual("A", NumberToExcelColumn(1));
Assert.AreEqual("Z", NumberToExcelColumn(26));
Assert.AreEqual("AA", NumberToExcelColumn(27));
Assert.AreEqual("AO", NumberToExcelColumn(41));
Assert.AreEqual("AZ", NumberToExcelColumn(52));
Assert.AreEqual("BA", NumberToExcelColumn(53));
Assert.AreEqual("ZZ", NumberToExcelColumn(702));
Assert.AreEqual("AAA", NumberToExcelColumn(703));
Assert.AreEqual("ABC", NumberToExcelColumn(731));
Assert.AreEqual("ACQ", NumberToExcelColumn(771));
Assert.AreEqual("AYZ", NumberToExcelColumn(1352));
Assert.AreEqual("AZA", NumberToExcelColumn(1353));
Assert.AreEqual("AZB", NumberToExcelColumn(1354));
Assert.AreEqual("BAA", NumberToExcelColumn(1379));
Assert.AreEqual("CNU", NumberToExcelColumn(2413));
Assert.AreEqual("GCM", NumberToExcelColumn(4823));
Assert.AreEqual("MSR", NumberToExcelColumn(9300));
Assert.AreEqual("OMB", NumberToExcelColumn(10480));
Assert.AreEqual("ULV", NumberToExcelColumn(14530));
Assert.AreEqual("XFD", NumberToExcelColumn(16384));
}
Sorry, this is Python instead of C#, but at least the results are correct:
def excel_column_number_to_name(column_number):
output = ""
index = column_number-1
while index >= 0:
character = chr((index%26)+ord('A'))
output = output + character
index = index/26 - 1
return output[::-1]
for i in xrange(1, 1024):
print "%4d : %s" % (i, excel_column_number_to_name(i))
Passed these test cases:
Column Number: 494286 => ABCDZ
Column Number: 27 => AA
Column Number: 52 => AZ
For what it is worth, here is Graham's code in Powershell:
function ConvertTo-ExcelColumnID {
param (
[parameter(Position = 0,
HelpMessage = "A 1-based index to convert to an excel column ID. e.g. 2 => 'B', 29 => 'AC'",
Mandatory = $true)]
[int]$index
);
[string]$result = '';
if ($index -le 0 ) {
return $result;
}
while ($index -gt 0) {
[int]$modulo = ($index - 1) % 26;
$character = [char]($modulo + [int][char]'A');
$result = $character + $result;
[int]$index = ($index - $modulo) / 26;
}
return $result;
}
Another VBA way
Public Function GetColumnName(TargetCell As Range) As String
GetColumnName = Split(CStr(TargetCell.Cells(1, 1).Address), "$")(1)
End Function
Here's my super late implementation in PHP. This one's recursive. I wrote it just before I found this post. I wanted to see if others had solved this problem already...
public function GetColumn($intNumber, $strCol = null) {
if ($intNumber > 0) {
$intRem = ($intNumber - 1) % 26;
$strCol = $this->GetColumn(intval(($intNumber - $intRem) / 26), sprintf('%s%s', chr(65 + $intRem), $strCol));
}
return $strCol;
}

Concatenate binaries then convert to int

string middlePart = "1111";
string leftPart = "0000";
string rightPart = "0000";
I want to concatenate all three of these together to make 000011110000, and convert that binary to a int.
The code below will not work because the number is way too big.
int maskingVal = Convert.ToByte((leftPart+middlePart+rightPart), 2);
Is there any way to do the Convert.ToByte on each individual part of the binary to int, and concatenate their binary equivalent to get the correct int value of 000011110000.
Thank you
I don't know why do you simply not do
var maskingVal = Convert.ToInt16((leftPart + middlePart + rightPart), 2);
but you can do it this way too
byte middlePart = Convert.ToByte("1111", 2);
byte leftPart = Convert.ToByte("0000",2);
byte rightPart = Convert.ToByte("0000",2);
var maskingVal = leftPart << 8 | middlePart << 4 | rightPart;
As indicated by Adriano Repetti, you can specify base 2:
int maskingVal = Convert.ToInt32(leftPart+middlePart+rightPart, 2);
string middlePart = "1111";
string leftPart = "0000";
string rightPart = "0000";
int leftVal = Convert.ToByte(leftPart, 2) * 256;
int middleVal = Convert.ToByte(middlePart, 2) * 16;
int rightVal = Convert.ToByte(rightPart, 2);
int maskingVal = leftVal + middleVal + rightVal;
You could just skip converting and calculate the value yourself.
string middlePart = "1111";
string leftPart = "0000";
string rightPart = "0000";
string combine = leftPart + middlePart + rightPart;
long value = 0;
for (int i = combine.Length - 1, exponent = 1; i >= 0; i--, exponent *= 2)
{
if (combine[i] == '1')
{
value += exponent;
}
}
Console.WriteLine(value);
Result:
240

Convert an integer to a binary string with leading zeros

I need to convert int to bin and with extra bits.
string aaa = Convert.ToString(3, 2);
it returns 11, but I need 0011, or 00000011.
How is it done?
11 is binary representation of 3. The binary representation of this value is 2 bits.
3 = 20 * 1 + 21 * 1
You can use String.PadLeft(Int, Char) method to add these zeros.
// convert number 3 to binary string.
// And pad '0' to the left until string will be not less then 4 characters
Convert.ToString(3, 2).PadLeft(4, '0') // 0011
Convert.ToString(3, 2).PadLeft(8, '0') // 00000011
I've created a method to dynamically write leading zeroes
public static string ToBinary(int myValue)
{
string binVal = Convert.ToString(myValue, 2);
int bits = 0;
int bitblock = 4;
for (int i = 0; i < binVal.Length; i = i + bitblock)
{ bits += bitblock; }
return binVal.PadLeft(bits, '0');
}
At first we convert my value to binary.
Initializing the bits to set the length for binary output.
One Bitblock has 4 Digits. In for-loop we check the length of our converted binary value und adds the "bits" for the length for binary output.
Examples:
Input: 1 -> 0001;
Input: 127 -> 01111111
etc....
You can use these methods:
public static class BinaryExt
{
public static string ToBinary(this int number, int bitsLength = 32)
{
return NumberToBinary(number, bitsLength);
}
public static string NumberToBinary(int number, int bitsLength = 32)
{
string result = Convert.ToString(number, 2).PadLeft(bitsLength, '0');
return result;
}
public static int FromBinaryToInt(this string binary)
{
return BinaryToInt(binary);
}
public static int BinaryToInt(string binary)
{
return Convert.ToInt32(binary, 2);
}
}
Sample:
int number = 3;
string byte3 = number.ToBinary(8); // output: 00000011
string bits32 = BinaryExt.NumberToBinary(3); // output: 00000000000000000000000000000011
public static String HexToBinString(this String value)
{
String binaryString = Convert.ToString(Convert.ToInt32(value, 16), 2);
Int32 zeroCount = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(binaryString.Length) / 8)) * 8;
return binaryString.PadLeft(zeroCount, '0');
}
Just what Soner answered use:
Convert.ToString(3, 2).PadLeft(4, '0')
Just want to add just for you to know. The int parameter is the total number of characters that your string and the char parameter is the character that will be added to fill the lacking space in your string. In your example, you want the output 0011 which which is 4 characters and needs 0's thus you use 4 as int param and '0' in char.
string aaa = Convert.ToString(3, 2).PadLeft(10, '0');
This may not be the most elegant solution but it is the fastest from my testing:
string IntToBinary(int value, int totalDigits) {
char[] output = new char[totalDigits];
int diff = sizeof(int) * 8 - totalDigits;
for (int n = 0; n != totalDigits; ++n) {
output[n] = (char)('0' + (char)((((uint)value << (n + diff))) >> (sizeof(int) * 8 - 1)));
}
return new string(output);
}
string LongToBinary(int value, int totalDigits) {
char[] output = new char[totalDigits];
int diff = sizeof(long) * 8 - totalDigits;
for (int n = 0; n != totalDigits; ++n) {
output[n] = (char)('0' + (char)((((ulong)value << (n + diff))) >> (sizeof(long) * 8 - 1)));
}
return new string(output);
}
This version completely avoids if statements and therfore branching which creates very fast and most importantly linear code. This beats the Convert.ToString() function from microsoft by up to 50%
Here is some benchmark code
long testConv(Func<int, int, string> fun, int value, int digits, long avg) {
long result = 0;
for (long n = 0; n < avg; n++) {
var sw = Stopwatch.StartNew();
fun(value, digits);
result += sw.ElapsedTicks;
}
Console.WriteLine((string)fun(value, digits));
return result / (avg / 100);//for bigger output values
}
string IntToBinary(int value, int totalDigits) {
char[] output = new char[totalDigits];
int diff = sizeof(int) * 8 - totalDigits;
for (int n = 0; n != totalDigits; ++n) {
output[n] = (char)('0' + (char)((((uint)value << (n + diff))) >> (sizeof(int) * 8 - 1)));
}
return new string(output);
}
string Microsoft(int value, int totalDigits) {
return Convert.ToString(value, toBase: 2).PadLeft(totalDigits, '0');
}
int v = 123, it = 10000000;
Console.WriteLine(testConv(Microsoft, v, 10, it));
Console.WriteLine(testConv(IntToBinary, v, 10, it));
Here are my results
0001111011
122
0001111011
75
Microsofts Method takes 1.22 ticks while mine only takes 0.75 ticks
With this you can get binary representation of string with corresponding leading zeros.
string binaryString = Convert.ToString(3, 2);;
int myOffset = 4;
string modified = binaryString.PadLeft(binaryString.Length % myOffset == 0 ? binaryString.Length : binaryString.Length + (myOffset - binaryString.Length % myOffset), '0'));
In your case modified string will be 0011, if you want you can change offset to 8, for instance, and you will get 00000011 and so on.

Convert a "big" Hex number (string format) to a decimal number (string format) without BigInteger Class

How to convert a "big" Hex number (in string format):
EC851A69B8ACD843164E10CFF70CF9E86DC2FEE3CF6F374B43C854E3342A2F1AC3E30C741CC41E679DF6D07CE6FA3A66083EC9B8C8BF3AF05D8BDBB0AA6CB3EF8C5BAA2A5E531BA9E28592F99E0FE4F95169A6C63F635D0197E325C5EC76219B907E4EBDCD401FB1986E4E3CA661FF73E7E2B8FD9988E753B7042B2BBCA76679
to a decimal number (in string format):
166089946137986168535368849184301740204613753693156360462575217560130904921953976324839782808018277000296027060873747803291797869684516494894741699267674246881622658654267131250470956587908385447044319923040838072975636163137212887824248575510341104029461758594855159174329892125993844566497176102668262139513
without using BigInteger Class (as my application should support machines without .NET Framework 4)?
Here's a quick-and-dirty implementation that can work with arbitrarily-large numbers. The aim of this implementation is simplicity, not performance; thus, it should be optimized drastically if it's to be used in a production scenario.
Edit: Simplified further per Dan Byström's implementation of the inverse decimal-to-hex conversion:
static string HexToDecimal(string hex)
{
List<int> dec = new List<int> { 0 }; // decimal result
foreach (char c in hex)
{
int carry = Convert.ToInt32(c.ToString(), 16);
// initially holds decimal value of current hex digit;
// subsequently holds carry-over for multiplication
for (int i = 0; i < dec.Count; ++i)
{
int val = dec[i] * 16 + carry;
dec[i] = val % 10;
carry = val / 10;
}
while (carry > 0)
{
dec.Add(carry % 10);
carry /= 10;
}
}
var chars = dec.Select(d => (char)('0' + d));
var cArr = chars.Reverse().ToArray();
return new string(cArr);
}
I just translated Douglas' code into VBA
Function HexToDecimal(ByVal sHex As String) As String
Dim dec() As Long
ReDim dec(0 To 0) As Long
Dim lCharLoop As Long
For lCharLoop = 1 To Len(sHex)
Dim char As String * 1
char = Mid$(sHex, lCharLoop, 1)
Dim carry As Long
carry = Val("&h" & char)
Dim i As Long
For i = 0 To UBound(dec)
Dim lVal As Long
lVal = dec(i) * 16 + carry
dec(i) = lVal Mod 10
carry = lVal \ 10
Next i
While (carry > 0)
ReDim Preserve dec(0 To UBound(dec) + 1) As Long
dec(UBound(dec)) = carry Mod 10
carry = carry \ 10
Wend
Next
For lCharLoop = UBound(dec) To LBound(dec) Step -1
Dim sDecimal As String
sDecimal = sDecimal & Chr$(48 + dec(lCharLoop))
Next
HexToDecimal = sDecimal
End Function
Private Sub TestHexToDecimal()
Debug.Assert HexToDecimal("F") = "15"
Debug.Assert HexToDecimal("4") = CStr(Val("&H4"))
Debug.Assert HexToDecimal("10") = CStr(Val("&H10"))
Debug.Assert HexToDecimal("20") = CStr(Val("&H20"))
Debug.Assert HexToDecimal("30") = CStr(Val("&H30"))
Debug.Assert HexToDecimal("40") = CStr(Val("&H40"))
Debug.Assert HexToDecimal("44") = CStr(Val("&H44"))
Debug.Assert HexToDecimal("FF") = "255"
Debug.Assert HexToDecimal("FFF") = "4095"
Debug.Assert HexToDecimal("443") = CStr(Val("&H443"))
Debug.Assert HexToDecimal("443C1") = "279489"
Debug.Assert HexToDecimal("443C1CE20DFD592FB374D829B894BBE5") = "90699627342249584016268008583970733029"
Debug.Assert HexToDecimal("EC851A69B8ACD843164E10CFF70CF9E86DC2FEE3CF6F374B43C854E3342A2F1AC3E30" & _
"C741CC41E679DF6D07CE6FA3A66083EC9B8C8BF3AF05D8BDBB0AA6CB3EF8C5BAA2A5" & _
"E531BA9E28592F99E0FE4F95169A6C63F635D0197E325C5EC76219B907E4EBDCD401FB1" & _
"986E4E3CA661FF73E7E2B8FD9988E753B7042B2BBCA76679") = _
"1660899461379861685353688491843017402046137536931563604625752175601309049219" & _
"5397632483978280801827700029602706087374780329179786968451649489474169926767" & _
"4246881622658654267131250470956587908385447044319923040838072975636163137212" & _
"8878242485755103411040294617585948551591743298921259938445664971761026682621" & _
"39513"
End Sub
Also a benchmark at statman.info Hexadecimal Conversion for large numbers
You can use the IntX library as it should work with .Net 2.0 and up. From the description on the page in regards to BigInteger:
So internally System.Numerics.BigInteger seems to use standard
arbitrary arithmetic algorithms and I am not worrying about IntX
library since, due to its use of FHT, it can be times faster for
really big integers.
The license is pretty liberal but worth reading first just to make sure it's okay.
I've not used this library but from a cursory glance at the source code this should be all you need to do
string dec = new IntX(myHex, 16).ToString();
If you don't want to compile the code yourself, you can install it via Nuget.
An easy way would be to use a big number library that supports your version of .NET. I'd recommend GnuMpDotNet, which uses the excellent GMP library. By default it targets .NET 3.5, but you can change that to .NET 2.0 without breaking anything (just remove the references and using statement that refer to new things), as it doesn't use anything from .NET 3.5. Here is an example using GnuMpDotNet:
BigInt e = new BigInt(hexString, 16);
string decimalStr = e.ToString();
Look at my answer here: https://stackoverflow.com/a/18231860/2521214
worth looking
string based conversions (limited by free memory only)
dec->hex and hex<-dec included
no bigint/bigreal lib used
supporting fixed point string formats (no exponents)
I just translated Douglas code to PHP:
function BigNumberHexToDecimal($hex)
{
$dec = array(0);
$hexLen = strlen($hex);
for($h=0;$h<$hexLen;++$h)
{
$carry = hexdec($hex[$h]);
for ($i = 0; $i < count($dec); ++$i)
{
$val = $dec[$i] * 16 + $carry;
$dec[$i] = $val % 10;
$carry = (int)($val / 10);
}
while ($carry > 0)
{
$dec[] = $carry % 10;
$carry = (int)($carry / 10);
}
}
return join("", array_reverse($dec));
}
I just translated Douglas code to JAVA:
public static String HexToDec(String hex) {
List<Integer> dec = new ArrayList<Integer>();
for (int k = 0; k < hex.length(); k++) {
String c = hex.charAt(k) + "";
int carry = Integer.parseInt(c, 16);
for (int i = 0; i < dec.size(); ++i) {
int val = dec.get(i) * 16 + carry;
dec.set(i, val % 10);
carry = val / 10;
}
while (carry > 0) {
dec.add(carry % 10);
carry /= 10;
}
}
int[] out = new int[dec.size()];
for (int i = 0; i < dec.size(); i++) {
out[i] = dec.get(i).intValue();
}
return arrayToDecString(reverseArray(out));
}
public static String arrayToDecString(int[] data) {
String str = "";
for (int i = 0; i < data.length; i++) {
str += data[i] + "";
}
return str;
}
public static int[] reverseArray(int[] data) {
for (int i = 0; i < data.length / 2; i++) {
int temp = data[i];
data[i] = data[data.length - i - 1];
data[data.length - i - 1] = temp;
}
return data;
}
I just translated Douglas code to Delphi/Pascal:
function HexToDecimal(const Hex: string): string;
var
dec: TList;
I: Integer;
carry: Cardinal;
c: Char;
val: Integer;
begin
Result := '';
dec := TList.Create;
try
dec.Add(Pointer(0)); // decimal result
for c in Hex do begin
carry := StrToInt('$' + c); // initially holds decimal value of current hex digit;
// subsequently holds carry-over for multiplication
for I := 0 to dec.Count -1 do begin
val := Integer(dec[I]) * 16 + carry;
dec[I] := Pointer(Integer(val mod 10));
carry := val div 10;
end;
while carry > 0 do begin
dec.Add(Pointer(Integer(carry mod 10)));
carry := carry div 10;
end;
end;
for I := 0 to dec.Count -1 do begin
val := Integer(dec[I]);
Result := IntToStr(val) + Result;
end;
finally
dec.Free;
end;
end;
procedure Test;
var
S: string;
begin
S := HexToDecimal('FF'); // 255
S := HexToDecimal('FFF'); // 4095
S := HexToDecimal('443C1'); // 279489
S := HexToDecimal('443C1CE20DFD592FB374D829B894BBE5'); // "90699627342249584016268008583970733029"
S := 'EC851A69B8ACD843164E10CFF70CF9E86DC2FEE3CF6F374B43C854E3342A2F1AC3E30' +
'C741CC41E679DF6D07CE6FA3A66083EC9B8C8BF3AF05D8BDBB0AA6CB3EF8C5BAA2A5' +
'E531BA9E28592F99E0FE4F95169A6C63F635D0197E325C5EC76219B907E4EBDCD401FB1' +
'986E4E3CA661FF73E7E2B8FD9988E753B7042B2BBCA76679';
S := HexToDecimal(S); // "166089946137986168535368849184301740204613753693156360462575217560130904921953976324839782808018277000296027060873747803291797869684516494894741699267674246881622658654267131250470956587908385447044319923040838072975636163137212887824248575510341104029461758594855159174329892125993844566497176102668262139513"
end;
Translated Douglas code to Qt:
QByteArray convertHexToDecimal(const QByteArray &hex)
{
QList<int> dec;
for (int i = 0; i < hex.count(); i++) {
int carry = hex.mid(i, 1).toInt(nullptr, 16);
for (int j = 0; j < dec.count(); ++j) {
int val = dec[j] * 16 + carry;
dec[j] = val % 10;
carry = val / 10;
}
while (carry > 0) {
dec.append(carry % 10);
carry /= 10;
}
}
QByteArray chars;
foreach (int d, dec) {
chars.prepend((char)('0' + d));
}
return chars;
}

ElGamal C# implementation

I want to implement ElGamal encryption. I need this for my school work but when I want do decryption the last step is always 0 cause of (b/Math.Pow(a,x))%primenumber is always less then 1.
Here is the keys generation:
public void GenerateKey() {
this.x = 3;
this.prvocislo = PrimeGen.findPrimes(29).Max(); //prime number
this.g = this.prvocislo % 12;
this.y = Convert.ToInt32(Math.Pow(this.g, this.x) % this.prvocislo);
this.k = 23;//601}
Here is encrypt function:
public string Encrypt(string word) {
List<string> words = new List<string>();
words = PrimeGen.SplitToArray(word, 2);
string encrypted="";
string sss = PrimeGen.GetStringFromBytes(PrimeGen.GetBytesFromInt(PrimeGen.GetIntFromBytes(PrimeGen.GetBytesFromString("ah")))); //returns ah so conversion works
foreach (string s in words)
{
int a = Convert.ToInt32(Math.Pow(g,k) % prvocislo);
int b = Convert.ToInt32((Math.Pow(y, k) * PrimeGen.GetIntFromBytes(PrimeGen.GetBytesFromString(s))) % prvocislo);
string aS = PrimeGen.GetStringFromBytes(PrimeGen.INT2LE(a + posun));
string bS = PrimeGen.GetStringFromBytes(PrimeGen.INT2LE(b + posun));
encrypted = encrypted + aS + bS;
}
return encrypted;
}
Here is my decrypt function:
public string Decrypt(string ElgamalEncrypted) {
string decrypted = "";
for (int i = 0; i < ElgamalEncrypted.Length; i = i + 2) {
string aS = ElgamalEncrypted.Substring(i, 2);
string bS = ElgamalEncrypted.Substring(i + 2, 2);
int a = PrimeGen.GetIntFromBytes(PrimeGen.GetBytesFromString(aS)) - posun;
int b = PrimeGen.GetIntFromBytes(PrimeGen.GetBytesFromString(bS)) - posun;
if(b==0) b=1;
if (a == 0) a = 1;
decrypted=decrypted+PrimeGen.GetStringFromBytes(PrimeGen.GetBytesFromInt(Convert.ToInt32(((b/Math.Pow(a,x))%prvocislo))));
}
return decrypted;
}
You're using Math.Pow(base, exponent) % modulus for modular exponentiation. That doesn't work because floating points can't represent the large integers crypto needs. Use System.Numerics.BigInteger.ModPow(base, exponent, modulus) instead.
The division probably doesn't work because you use integer division, instead of multiplying with the modular multiplicative inverse of the right side.

Categories

Resources