Reversing Integers

If you have questions about any aspect of QBasic programming, or would like to help fellow programmers solve their problems, check out this board!

Moderators: Pete, Mods

Post Reply
vbgirl1420
Newbie
Posts: 1
Joined: Sat Mar 15, 2008 7:51 pm

Reversing Integers

Post by vbgirl1420 »

Is there a command which will reverse the order of an integer? For example, if x%=12345, I would like a command to switch x% to 54321. I also tried converting the integer to a string and reversing it, but I cannot find a way to convert the string back to an integer. Thanks in advance.

Jenna
moneo
Veteran
Posts: 451
Joined: Tue Jun 28, 2005 7:00 pm
Location: Mexico City, Mexico

Post by moneo »

If you already converted the number to a string and reversed the digits, then use the VAL function to convert the new string to a numeric value.

Example:
NEWVALUE = VAL(NEWSTRING$)

Regards..... Moneo
User avatar
burger2227
Veteran
Posts: 2466
Joined: Mon Aug 21, 2006 12:40 am
Location: Pittsburgh, PA

Post by burger2227 »

Perhaps you can also use STR$(number%) to convert a number to a string. You should use LTRIM$ to eliminate the space before a positive number like this:

num$ = LTRIM$(STR$(number))

Then use MID$ to rearrange each letter in the number in a counter loop.

To convert a string to a number use VAL as already shown. VAL only works for string numbers, spaces and a period for decimal values. Letters will stop the value returned when encountered. DO NOT use Commas as QB does not use them! IE: 100000 instead of 100,000.

Ted
Please acknowledge and thank members who answer your questions!
QB64 is a FREE QBasic compiler for WIN, MAC(OSX) and LINUX : https://www.qb64.org/forum/index.php
Get my Q-Basics demonstrator: https://www.dropbox.com/s/fdmgp91d6h8ps ... s.zip?dl=0
moneo
Veteran
Posts: 451
Joined: Tue Jun 28, 2005 7:00 pm
Location: Mexico City, Mexico

Post by moneo »

burger2227 wrote:Perhaps you can also use STR$(number%) to convert a number to a string. You should use LTRIM$ to eliminate the space before a positive number like this:

num$ = LTRIM$(STR$(number))

Then use MID$ to rearrange each letter in the number in a counter loop.

To convert a string to a number use VAL as already shown. VAL only works for string numbers, spaces and a period for decimal values. Letters will stop the value returned when encountered. DO NOT use Commas as QB does not use them! IE: 100000 instead of 100,000.

Ted
Ted is right. Before using a VAL function you should validate the string numbers. The same holds true for using the STR$ function. In general, you should always validate user input that is supposed to be strictly numeric.

Regards..... Moneo
Post Reply