### Random bug

An example of a problem which could occur when using untyped variables :
Converting a decimal number (range : 0 to 255) in hexadecimal.
We 'll display the result in a dynamic text.

Hexadecimal numbres are 16-basis, thus we yield 0123456789ABCDEF
( A =10, B=11, C=12, D=13, E=14, F=15 )
For instance 255 = (15)x16 + (15) gives FF.
127 = (7)x16 + (15) gives 7F.
We need to merge the 2 in a dynamic text variable.
For the higher byte, x = (number >> 4) gives an integer
For the lower byte, we get the rest, either y = number - (x << 4)
Then txtdyn = x + y.
If x and y are in (0....9) , we 'll yield the sum !
We don't want this !
ex : 120 = (7)x16 + 8 ===> 78 hexa
but txtdyn 'll display 7+8 = 15 !!!
In other cases, no trouble because of characters A...F
In other way, we 'd yield a random bug, depending on number.

The right way:
function dec2hex( xxx )
{
if ( xxx == 0 ) return "00"; // get off right now

hexchar ="0123456789ABCDEF"; // all hexa chars

yyy = (xxx >> 4); // number /16
hb = hexchar.charAt(yyy); // high byte
zzz = xxx - (yyy << 4);
lb = hexchar.charAt(zzz); // low byte
str = String(hb) add String(lb); // transtyping !
// works anytime !
return str.toUpperCase();
}

Call : txtdyn = dec2hex( a_number );

Si vous aimez le site

Select a language if you need :

Page chargée en 0.002 sec.

Dernière Modification : Jeu 21 Mars 2019 18:51
Copyright © 1999-2019 Jean-Paul Molina Tous droits réservés.