473,799 Members | 3,671 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Get Value of Digit


I have a Graphical User Interface program and I'm working with numbers
written in base-10.

Is there a better way than the following to get the digit value?

unsigned GetDigitValue( char const c )
{
switch ( c )
{
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
}

}

Any reason why the above code wouldn't be fully portable?

-Tomás

Mar 1 '06 #1
7 2383
Tomás wrote:
I have a Graphical User Interface program and I'm working with numbers
written in base-10.

Is there a better way than the following to get the digit value?

unsigned GetDigitValue( char const c )
{
switch ( c )
{
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
}

}

Any reason why the above code wouldn't be fully portable?

-Tomás


Assuming you've already done error checking so you're sure the
character is between '0' and '9', you could just do this:

return unsigned(c - '0');

Your code is indeed portable, albeit inelegant.

Cheers! --M

Mar 1 '06 #2
mlimber wrote:
Tomás wrote:
I have a Graphical User Interface program and I'm working with numbers
written in base-10.

Is there a better way than the following to get the digit value?

unsigned GetDigitValue( char const c )
{
switch ( c )
{
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
}

}

Any reason why the above code wouldn't be fully portable?

-Tomás

[snip] Your code is indeed portable, albeit inelegant.


.... and, to emphasize the point, possibly incorrect if you haven't done
error checking on c before entering this function. (What would happen
if c had a value of 'a'?)

Cheers! --M

Mar 1 '06 #3
There are some character tables (ASCII, EBCDIC, ....), and you can't
assume what position occupies numeric characters. But in practice, in
all examples I know they have consecutive positions.
If you assume that, you can calcule offset with the first element:
Example:

You can get value 0 with the operation 0 - '0'
Then you can write your own sentence:
return c-'0'

I can't assure that in all the cases, numbers are consecutive in any
codification, but in all cases I know, they are.

There are other alternatives:
- using C's sscanf, but you must use a null terminating string
- using stringstream (you can construct a stringstream and then use the
operator >> )

Tomás wrote:
I have a Graphical User Interface program and I'm working with numbers
written in base-10.

Is there a better way than the following to get the digit value?

unsigned GetDigitValue( char const c )
{
switch ( c )
{
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
}

}

Any reason why the above code wouldn't be fully portable?

-Tomás

Mar 1 '06 #4
On 2006-03-01 09:17:30 -0500, Carlos Martinez Garcia
<cm****@nospam. tid.es> said:
There are some character tables (ASCII, EBCDIC, ....), and you can't
assume what position occupies numeric characters. But in practice, in
all examples I know they have consecutive positions.
If you assume that, you can calcule offset with the first element:
Example:

You can get value 0 with the operation 0 - '0'
Then you can write your own sentence:
return c-'0'

I can't assure that in all the cases, numbers are consecutive in any
codification, but in all cases I know, they are.


You *can* be sure that numbers are consecutive, as the standard
requires it. If c is a digit, then (c-'0') is guaranteed to produce the
value of that digit.
--
Clark S. Cox, III
cl*******@gmail .com

Mar 1 '06 #5


I know a lot of people here seem to dismiss my efforts as "over-zealous
optimization", but considering the two alternatives:

unsigned GetDigitValue( char const c )
{
switch ( c )
{
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
}

}

unsigned GetDigitValue( char const c )
{
return c - '0';
}

Firstly, the first one would produce longer assembly code, right?
But which would execute faster. Let's say this function is used inline, and
that it's called several times a second as it's decoding Gigabytes of
information... which do you think would be faster?

My guess is that the second would be faster.

How do you usually test the speed of code, say if you've two functions that
achieve an aim by different methods?

-Tomás
Mar 1 '06 #6
Tomás wrote:
I know a lot of people here seem to dismiss my efforts as "over-zealous
optimization", but considering the two alternatives:

unsigned GetDigitValue( char const c )
{
switch ( c )
{
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
}

}

unsigned GetDigitValue( char const c )
{
return c - '0';
}

Firstly, the first one would produce longer assembly code, right?
Probably.
But which would execute faster. Let's say this function is used inline, and
Well, the second is really easy to inline.
that it's called several times a second as it's decoding Gigabytes of
information... which do you think would be faster?
The second one.
My guess is that the second would be faster.

How do you usually test the speed of code, say if you've two functions that
achieve an aim by different methods?


Stick it in a loop and do it a million times. Your OS probably has
higher resolution timers than C++, so use the most appropriate.

Ben Pope
--
I'm not just a number. To many, I'm known as a string...
Mar 1 '06 #7

Tomás wrote:
I know a lot of people here seem to dismiss my efforts as "over-zealous
optimization", but considering the two alternatives:

unsigned GetDigitValue( char const c )
{
switch ( c )
{
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
}

}

unsigned GetDigitValue( char const c )
{
return c - '0';
}

Firstly, the first one would produce longer assembly code, right?
But which would execute faster. Let's say this function is used inline, and
that it's called several times a second as it's decoding Gigabytes of
information... which do you think would be faster?

My guess is that the second would be faster.

How do you usually test the speed of code, say if you've two functions that
achieve an aim by different methods?

-Tomás


The 2nd implementation will be much faster because branching code often
leads to CPU pipeline stalls and dramatically decreases performance.
Although CPU branch prediction engine can alleviate some of the
problems but it's best to write code that contains no branching as in
implementation 2.

Mar 1 '06 #8

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

Similar topics

3
4530
by: Phil Powell | last post by:
My first time working with a PHP class, and after 6 hours of working out the kinks I am unable to return a value from the class, so now I appeal to the general audience what on earth did I do wrong this time? This is the code the retrieves the values: if (($hasRegistered || $hasPreRegistered) && !empty($uplinenumber)) { // CHECK TO SEE IF UPLINE NUMBER IS A VALID NUMBER $regNumberGenerator = new RegNumberGenerator($uplinenumber,...
1
14158
by: G Kannan | last post by:
Hey all! I have written a perl script to retrieve information from a HTML Form and insert the data into an Oracle database table. I am gettting the the following error message: "Use of uninitialized value in concatenation (.) at register.pl line 38, <STDIN> line 10." The PERL code is as follows:
3
1426
by: JKop | last post by:
Consider the following platform: char = 8-bit short = 16-bit int = 32-bit long = 32-bit
9
2937
by: ckerns | last post by:
I want to loop thru an array of controls,(39 of them...defaults = 0). If value is null or non-numeric I want to assign the value of "0". rowString = "L411" //conrol name if (isNaN(eval ("document.forms."+rowString+".value")) == true ) { //this alert works if the value is a letter,i.e,"a" alert("You have entered an non-numeric value.\nEnter a number in the appropriate box.");
14
2108
by: TTroy | last post by:
Hello, can anyone explain why the following function will not work for INT_MIN: /* itoa: convert n to characters in s */ void itoa(int n, char s) { int i, sign; if((sign = n) < 0) /* record sign */
6
14190
by: Tony Tortora | last post by:
I am writing and add on application. The application uses Unique IDs and they are stored in Base 26 (ie 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ). 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#.
6
1510
by: Michael.McD | last post by:
Hi, I want to create a type that behaves like in integer but only allows assignment of say 3 digit integers where attempts to assign values greater or loess will throw an exception. E.g. int threeDigitInteget = 7; will throw an exception. I can achive this behaviour through the new types constructor but cannot work out how to intercept assignments using the = assignment operator.
4
7834
by: spebola | last post by:
I am using vb.net 2003 professional and I get the following results when using the round method: dim Amount as decimal = 180.255 Amount = Amount.Round(Amount, 2) Amount now contains 180.25. I need it to contain 180.26. Any ideas?
5
2546
by: eyoung | last post by:
I have a function to check a string to make sure it is 6 digites using the trigger onBlur="CkFrmt(this)" Problem is I've got 4 fields in a row...if I enter a wrong number in the first and hit tab I get the error message and my script tries to move the focus to the first item...but because I hit the tab the focus in already on the second item which does not contain a 6 digit value so I must kill the page. help! function CkFrmt(str) {
0
10488
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10237
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10029
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9077
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 project—planning, coding, testing, and deployment—without 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
7567
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
5588
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4144
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
3761
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2941
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.