473,809 Members | 2,591 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Character Value with Base 26 with C#

I am writing and add on application. The application uses Unique IDs and
they are stored in Base 26 (ie 0123456789ABCDE FGHIJKLMNOPQRST UVWXYZ).
I am having trouble reading the decimal value of a character of the key and
to assign a the new value for the Unique ID.

For example to change "A" to "B". Normally, I would read the ASCII value of
"A" which is 65, add one making it 66 which is "B".

How can I do this is C#.

Thanks
Nov 15 '05 #1
6 14193
On Thu, 29 Jan 2004 12:03:50 -0500, Tony Tortora wrote:
I am writing and add on application. The application uses Unique IDs and
they are stored in Base 26 (ie 0123456789ABCDE FGHIJKLMNOPQRST UVWXYZ).
I am having trouble reading the decimal value of a character of the key and
to assign a the new value for the Unique ID. For example to change "A" to "B". Normally, I would read the ASCII value of
"A" which is 65, add one making it 66 which is "B". How can I do this is C#. Thanks


I assume that you are trying to convert to and from Base 26 encoding.
Here is some sample code that does that for unsigned integers. If you
prefer lower case, just modify accordingly.

Begin snippet
-------------
static string ConvertToBase26 (uint i) {
const int BASE = 26;
StringBuilder result = new StringBuilder() ;
uint remainder;

while (i > 0) {
remainder = i % BASE;
i = i / BASE;
result.Insert(0 , (char)((char)re mainder + 'A'));
};

return result.ToString ();
}

static uint ConvertFromBase 26(string val) {
const double BASE = 26.0;
uint ret = 0;

char[] vals = val.ToUpper().T oCharArray();
int last = vals.Length - 1;

for (int x = 0; x < vals.Length; x++) {
if (vals[x] < 'A' || vals[x] > 'Z')
throw new ArgumentExcepti on("Not a valid Base26 string.", val);

ret += (uint)(Math.Pow (BASE, (double)x) * (vals[last - x] - 'A'));
}

return ret;
}
-----------
End snippet

HTH,
Tim
--
Tim Smelser - MVP Visual C#
To email me, make the snot hot.
Nov 15 '05 #2
That's good, but both of you guys are missing a fundamental point here:
"0123456789ABCD EFGHIJKLMNOPQRS TUVWXYZ" is 36 chars, not 26!
With a base of 26, the last usable char will be 'P', not 'Z' as in base 36.

I came up with a routine back in my VB days that allows the one-way
conversion from decimal to base whatever. I converted this to C#, and
I'm sure with a little thought it could be modified to be more efficient,
but I'm feeling lazy right now, so I'll just post what I have now:

public string chBase(int x, int Base)
{
int modx = 0;
string retVal = string.Empty;

if(x == 0)
return "0";
if(x < 0)
return ""; // Error
while(x > 0)
{
modx = x % Base;
if(modx < 10)
retVal = modx.ToString() + retVal;
else
retVal = Convert.ToChar( modx + 55) + retVal;
x = x / Base;
}
return retVal;
}

No fancy error checks or anything, but when I wrote this I knew that I
would always be passing correct values. Even so, I did add the checks
for 0 and < 0.
I assume that you are trying to convert to and from Base 26 encoding.
Here is some sample code that does that for unsigned integers. If you
prefer lower case, just modify accordingly.

Begin snippet
-------------
static string ConvertToBase26 (uint i) {
const int BASE = 26;
StringBuilder result = new StringBuilder() ;
uint remainder;

while (i > 0) {
remainder = i % BASE;
i = i / BASE;
result.Insert(0 , (char)((char)re mainder + 'A'));
};

return result.ToString ();
}

static uint ConvertFromBase 26(string val) {
const double BASE = 26.0;
uint ret = 0;

char[] vals = val.ToUpper().T oCharArray();
int last = vals.Length - 1;

for (int x = 0; x < vals.Length; x++) {
if (vals[x] < 'A' || vals[x] > 'Z')
throw new ArgumentExcepti on("Not a valid Base26 string.", val);

ret += (uint)(Math.Pow (BASE, (double)x) * (vals[last - x] - 'A'));
}

return ret;
}
-----------
End snippet

HTH,
Tim
--
Tim Smelser - MVP Visual C#
To email me, make the snot hot.

Nov 15 '05 #3
On Thu, 29 Jan 2004 17:01:53 -0500, Gary Morris wrote:
That's good, but both of you guys are missing a fundamental point here:
"0123456789ABCD EFGHIJKLMNOPQRS TUVWXYZ" is 36 chars, not 26!
With a base of 26, the last usable char will be 'P', not 'Z' as in base 36. I came up with a routine back in my VB days that allows the one-way
conversion from decimal to base whatever. I converted this to C#, and
I'm sure with a little thought it could be modified to be more efficient,
but I'm feeling lazy right now, so I'll just post what I have now: public string chBase(int x, int Base)
{
int modx = 0;
string retVal = string.Empty; if(x == 0)
return "0";
if(x < 0)
return ""; // Error
while(x > 0)
{
modx = x % Base;
if(modx < 10)
retVal = modx.ToString() + retVal;
else
retVal = Convert.ToChar( modx + 55) + retVal;
x = x / Base;
}
return retVal;
} No fancy error checks or anything, but when I wrote this I knew that I
would always be passing correct values. Even so, I did add the checks
for 0 and < 0.


Base 26 (in all of the references I have ever found for it) has no
numbers. It is simply using the letters of the alphabet as a numerical
representation. That is why I stipulated my assumption that Base 26 is
actually what Tony wanted (since, as you noted, the character set he
posted was a base 36).

Tim
--
Tim Smelser - MVP Visual C#
To email me, make the snot hot.
Nov 15 '05 #4
First, that's base 36, I believe.

Second, you can access a string by index and return a character, which can
be cast directly to an iteger.

To get the Unicode (rather than ASCII in .NET) value of the third character
of a string, for example, you would use:

string myString = "SOMESTRING ";
int code = (int)myString[2];

Luckily, the basic alphabet has the same code points in Unicode as they do
in ASCII. Still, you may want to do subtraction from the char literal 'A'
to make the code more readable.

int result = 0;
int factor = 1;

for(int index = myString.Length ; index >= 0; index--) {

int digitValue = 0;
char digit = myString[index];

if(Char.IsDigit (digit))
{
digitValue = (int)(digit) - (int)('0');
}
else if(Char.IsUpper (digit))
{
digitValue = 10 + (int)(digit) - (int)('A');
}
else if(Char.IsLower (digit))
{
digitValue = 10 + (int)(digit) - (int)('a');
}

result += factor * digitValue;
factor *= 36;

}

// result contains the converted number

I haven't tested that code, so you'll want to try it yourself and possibly
optimize it or make it your own. You might overflow an Int32 pretty quickly
so you may need to use 64-bit math.

--Matthew W. Jackson

"Tony Tortora" <AT@att.com> wrote in message
news:e%******** ********@TK2MSF TNGP11.phx.gbl. ..
I am writing and add on application. The application uses Unique IDs and
they are stored in Base 26 (ie 0123456789ABCDE FGHIJKLMNOPQRST UVWXYZ).
I am having trouble reading the decimal value of a character of the key and to assign a the new value for the Unique ID.

For example to change "A" to "B". Normally, I would read the ASCII value of "A" which is 65, add one making it 66 which is "B".

How can I do this is C#.

Thanks

Nov 15 '05 #5
OOOPS!

On my example, change "myString.Lengt h" to "myString.Lengt h - 1"

I actually don't write too many backwards for loops.

If there had been a reverse foreach, I would have used that. :-)

--Matthew W. Jackson
Nov 15 '05 #6
Thanks for all your help. I tried to do a fancy solution. I was having
trouble so I took a simple solution that works.

Here is my solution if you ar interested.

private string AddOneBase36(st ring MNumber)
{
bool MAddOne;
string MNewKey;
int MCounter;
int MIndex;

string MResult;
string MBase36 = "0123456789ABCD EFGHIJKLMNOPQRS TUVWXYZ";
MResult = "";
MNewKey = "";
MAddOne = true;

for (MCounter = MNumber.Length-1; MCounter >= 0 ; MCounter--)
{
MIndex = MBase36.IndexOf (MNumber[MCounter]);

if (MAddOne)
{
if (MIndex == MBase36.Length - 1)
{
MIndex = 0;
MAddOne = true;
}
else
{
MIndex++;
MAddOne = false;
}
}

MNewKey = MNewKey + MBase36[MIndex];

}
for (MCounter = MNewKey.Length-1 ; MCounter >= 0; MCounter--)
{
MResult = MResult + MNewKey[MCounter];
}

return MResult;

}

"Matthew W. Jackson" <th************ ********@NOSPAM .NOSPAM> wrote in message
news:%2******** ********@TK2MSF TNGP09.phx.gbl. ..
OOOPS!

On my example, change "myString.Lengt h" to "myString.Lengt h - 1"

I actually don't write too many backwards for loops.

If there had been a reverse foreach, I would have used that. :-)

--Matthew W. Jackson

Nov 15 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1864
by: kamp | last post by:
Hello, Below is a snippet from a schema. The second enumeration should contain an i umlaut (archasch) but when I use this schema with Altova's Stylevision software the iumlaut is not displayed properly. So I changed it into a character entity. I tried several entity declarations (examples found on the web) but none of them worked i.e. Stylevision refused to load the schema. So, I want to know the following: is it possible to use...
9
2639
by: Erik Leunissen | last post by:
L.S. I've observed unexpected behaviour regarding the usage of the '#' flag in the conversion specification in the printf() family of functions. Did I detect a bug, or is there something wrong with my expectations regarding the effect of the following code: printf("NULL as hex: %#4.2x\n", '\0');
6
1811
by: Lucvdv | last post by:
In a sorted list, certain characters are grouped together, for example "b" (cedille b) comes after "ca" but before "cc". Is there a built-in way to find out what 'base character', such as C for cedille, a character belongs to for a given globalization setting?
0
3168
by: Phil C. | last post by:
(Cross post from framework.aspnet.security) Hi. I testing some asp.net code that generates a 256 bit Aes Symmetric Key and a 256 bit entropy value. I encrypt the Aes key(without storing it as Base64) with the host's dpapi using the entropy value(without storing it as Base64), and then store the encrypted Aes key value and the entropy value in some SHARED VARIABLES AS BYTE ARRAYS(not Base64). I then decrypt the stored encrypted Aes...
6
9660
by: Claude Henchoz | last post by:
Hi guys I have a huge list of URLs. These URLs all have ASCII codes for special characters, like "%20" for a space or "%21" for an exclamation mark. I've already googled quite some time, but I have not been able to find any elegant way on how to replace these with their 'real' counterparts (" " and "!"). Of course, I could just replace(), but that seems to be a lot of work.
1
2376
by: =?Utf-8?B?UGF1bCBQaGlsbGlwcw==?= | last post by:
I have read many things about this but I haven't got a clear vision on what to do if anything about this. I have a system that tries to find holes in my web site. One of the things it has found and has been sent to me is an Invalid_Viewstate exception. I will provide the stack trace below. If you read down the stack trace it talks about "Invalid chararcter in a base-64
1
3186
by: banagani | last post by:
Hi All, I am facing an issue in the XmlTextWriter class in the dotnet 2.0. This is the sample code Actual XML is like this <Name>&#x8A73;&#x7D30;&#x4ED5;&#x69D8;&#x306B;</Name>
3
3093
by: =?Utf-8?B?Vmlub2Q=?= | last post by:
Hi All, I am facing an issue in the XmlTextWriter class in the dotnet 2.0. This is the sample code Actual XML is like this <Name>詳細仕様に</Name>
11
1921
by: Fred Chateau | last post by:
I found the following code in an online tutorial, and I'm having some difficulty understanding it. Unfortunately, it did not list any expected output examples for val. What type is val? Is this statement comparing, adding, and subtracting ASCII numbers? if ('0' <= ch && ch <= '9') val = ch - '0'; else if ('A' <= ch && ch <= 'Z') val = 10 + ch - 'A'; else {val = 0; Console.WriteLine("invalid character {0}", ch);}
0
9722
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
10378
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9200
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7664
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6881
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4333
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3862
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3015
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.