Vous êtes sur la page 1sur 18

Programmation Orientée Objet avec JAVA

TP N°2
Représentation interne des types de données Scalaires
Et types d'erreur

Objectif du TP :
 Etudier les méthodes de représentation interne des types de données numériques scalaires
o Pour les entiers : Complément à 2
o Pour les réels : IEEE754 simple précision(float) et double précision(double).
 Ecrire le code qui fait appel à l'API de Java pour effectuer les deux conversions suivantes:
o Représentation interne
o Déterminer les intervalles de données représentés par chacun des type
 Comprendre les valeurs spéciales de float et double (NaN, infinity, -infinity).
 Comprendre que les types float et double ne représentent pas un ensemble infini (continue) de valeurs
mais un ensemble fini (discret) de valeurs. Déterminer l'écart entre deux float et entre deux double
consécutifs.
 Etudier le problème des débordements
 Distinguer les 3 types d'erreurs dans un programme : de compilation, d'exécution et de logique
 Bien comprendre la page 21 ci-dessous sur le site :

http://www.pitt.edu/~juy9/142/slides/L3-FP_Representation.pdf
Rappel:
Java fournit 8 types de données primitifs résumés dans le tableau ci-dessous :
Types de données primitifs
MotClé Description-Taille/Format Intervalle
Entiers
byte Entier signé sur 1octet en Cà2 -27 (-128) à + 27-1(127)
short Entier signé sur 2 octets en Cà2 -215(-32768)à + 215-1
int Entier signé sur 4 octets en Cà2 -231 à + 231-1
long Entier signé sur 8 octets en Cà2 -263 à + 263-1

Réels
Réel en virgule flottante simple précision sur -3.4..e38 à -1.4..e-45 (Partie négative)
float
4 octets (IEEE 754) 1.4..e-45 à 3.4..e38 (Partie positive)
Réel en virgule flottante double précision sur -1.7…e308 à -4.9…e-324 (Partie négative)
double
8 octets (IEEE 754) 4.9…e-324 à 1.7…e308 (Partie positive)

Autres types
char Un seul caractère sur 2 octets (Unicode) Code unicode de 0 à 65535
boolean Valeur boolèene sur 1 bit true or false

Partie I : Représentation des entiers et opérateurs bit à bit et de décalage.


Exercice 1 :
Ecrire une classe EntiersIntervallesDebordemnt qui contient uniquement la méthode main pour réaliser
les tâches ci-dessous :
 Afficher les valeurs minimales et maximales de chaque type entier.
 Incrémenter avec l'opérateur ++ la valeur maximale de chaque type. Obtenez-vous un
débordement ? Pourriez-vous expliquer la valeur obtenue ?
 Décrémenter avec l'opérateur -- la valeur minimale de chaque type. Obtenez-vous un
débordement ? Pourriez-vous expliquer la valeur obtenue ?
 Utiliser les méthodes de la classe Math pour détecter les débordements
Exercice 2 :
Ecrire une classe EntiersreprésentationInterne qui contient uniquement la méthode main pour réaliser les
tâches ci-dessous :
 Lire au clavier une valeur positive et une valeur négative de chaque type entier (bytePositif,
byteNegatif, shortPositif, shortNegatif, intPositif, intNegatif, longPositif, et longNegatif).
 Affiche pour chaque valeur lue sa représentation interne en binaire et en hexadécimal.
 Effectuer un décalage de 2 vers la droite avec les deux opérateurs >> et >>> et vers la gauche des
valeurs positives et négatives de type byte et int.
Expliquez les résultats obtenus.
Expliquez la différence entre les opérateurs >> et >>>.
 Effectuer les opérations binaires NOT, Complément à 1, ET et OU ente les deux valeurs positives et
négatives de chacun des types short et int. Expliquez le résultat.
Partie II : Représentation interne des réels (float et double)
Les données de type réel sont représentés dans la mémoire en utilisant avec la notation IEEE754.

Pour de plus amples informations sur la notation IEEE754 consulter le site :


http://www.pitt.edu/~juy9/142/slides/L3-FP_Representation.pdf

Pour les données de type float la notation IEEE754 simple précision utilise 32 bits:

B31 B30 B29 B28 B27 B26 B25 B24 B23 B22 B21 B20 B19 B18 B17 B16 B15 B14 B13 B12 B11 B10 B9 B8 B7 B6 B5 B4 B3 B2 B1 B0

B31 : Bit de signe = 0 pour un nombre positif et 1 pour un nombre négatif

B30 B29 B28 B27 B26 B25 B24 B23 : représentent l'exposant en excédent à 127.

B22 B21 B20 B19 B18 B17 B16 B15 B14 B13 B12 B11 B10 B9 B8 B7 B6 B5 B4 B3 B2 B1 B0 : représentent la partie fractionnaire de la
mantisse

La valeur du nombre est :

(-1)signe x 1.Mantisse x 2 Exposant


Rappel:
a-La représentation d'un entier N en excédent à 127 sur 8 bits est obtenue en représentant l'entier (N + 127) en
binaire naturelle sur 8 bits.
Exemple :
Pour un exposant = 4.
Sa représentation en excédent à 127 est : 4+127 = 131 = 128 + 2 +1 = 10000011 en Binaire Naturelle.
y
b- Le format normalisé d'un nombre réel en base 10 est : 1 2 3 4 x .x x x ……… 10 avec x1 # 0.
Un nombre réel en binaire est représenté en format normalisé comme en base 10.
Par exemple un float ayant la représentation interne ci-dessous :
31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
0 1 0 0 0 1 0 1 1 1 1 1 0 1 0 0 1 0 0 0 1 1 0 0 1 0 0 1 1 0 1 0
Exposant en excédent à 127
signe
=139 Mantisse

A pour valeur en base 10 :

(-1)signe x 1.Mantisse x 2(Exposant-127)


= +1,111101001000110010011010 x 2(139 - 127)
Le 1 à gauche de la virgule (qui est souligné) n'est pas représenté en mémoire (C'est une astuce pour augmenter la
précision. Ainsi la mantisse est représentée sur 24 bits au lieu de 23 bits).

La représentation normalisée a pour principal objectif de représenter un nombre par une seule représentation
binaire (un seul pattern de bits).

La représentation de l'exposant en excédent à 127 (en excédent à 1023 pour le double) permet de simplifier la
comparaison de deux floats. En effet si les exposants de deux floats (double) ne sont pas les mêmes, l'ordre de ces
exposants permet de déterminer l'ordre des floats (doubles) correspondants.
Le site ci-dessous permet de donner la représentation d'un float en IEEE754 Simple précision.

https://www.h-schmidt.net/FloatConverter/IEEE754.html
Exemple de représentation:
a-Représentation de +17F en IEEE754 Simple précision : 17(10) = 10001(2) = 1,0001 x 24(2)

Signe = 0 31
(bit de signe = 0 si nombre >0; =1 si nombre <0) 0

Exposant = 4 (L'exposant est représenté en excèdent à 127. 30 29 28 27 26 25 24 23


(4+127 = 131 en Binaire naturel) 1 0 0 0 0 0 1 1
Mantisse = 0001000000000000000000 (le 1 à gauche de la virgule n'est pas représenté)
22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

b-Représentation de -17F en IEEE754 Simple précision : -17(10) = 10001(2) = -1,0001 x 24(2)

La représentation de -17 est identique à celle de +17 sauf que le bit de signe est 1 et non 0.
c-Représentation de 0.125F en IEEE754 Simple précision : +0.125(10) = 0.001 = 1,0 x 2-3(2)

31
Signe = 0 (Nombre >0)
0

Exposant = -3 (L'exposant est représenté en excèdent à 127. 30 29 28 27 26 25 24 23


(-3+127 = 124 en Binaire naturel) 0 1 1 1 1 1 0 0
Mantisse = 0000000000000000000000 (le 1 à gauche de la virgule n'est pas représenté)
22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
d- Représentation de 0.15F en IEEE754 Simple précision
0,15(10) = 0, 0 0 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1
1, 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 x 2-3(2)

31
Signe = 0 (Nombre >0)
0

Exposant = -3 (L'exposant est représenté en excèdent à 127. (- 30 29 28 27 26 25 24 23


3+127 = 124 en Binaire naturel) 0 1 1 1 1 1 0 0

22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
Mantisse =
0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1
Remarque : le site ne donne pas la même valeur????
Exercice 3 : Représentation des valeurs spéciales de l'IEEE754 Simple précision

Le tableau ci-dessous donne la représentation des valeurs spéciales, 0, NaN, +infinity, -infinity , et des valeurs non
normalisées.

Ecrire une classe IEEE754SPVS (SPVS : Simple Précision Valeurs Spéciales) qui permet d'afficher la représentation
interne des valeurs spéciales d'un float : NaN, POSITVE_INFINITY (+infinity), NEGATIVE_INFINITY (-infinity) et d'une
valeur non normalisée comme -0.5x2-126 et 0.25 x 2-126 .
La classe doit aussi permettre de calculer ces valeurs à partir de leur représentation interne.

Le site https://www.h-schmidt.net/FloatConverter/IEEE754.html donne les résultats ci-dessous:

Représentation de 0

Représentation de NaN (Not a Number)


Représentation de +Infinity

Représentation de -Infinity

Représentation des valeurs non normalisées (fournis dans le tableau ci-dessous):


Représentation IEEE754 (hexadécimale) Valeur réelles en base 10
Valeur positive minimale 0x00400000 5.877472E-39
Valeur positive maximale 0x007FFFFF 1.1754942E-38
Valeur négative minimale 0x80400000 -1.1754942E-38
Valeur négative maximale 0x807FFFF -5.877472E-39
Exercice 4 : Représentation des valeurs normalisées de l'IEEE754 Simple précision

La partie colorée en gris du tableau ci-dessous correspond aux float qui sont représentés avec la notation IEEE754
normalisée.

Ecrire une classe Java IEEE754SimplePrecisionValeursNormales qui permet, en utilisant l'API, de lire au clavier une
valeur de type float puis d'afficher sa représentation interne en binaire et en hexadécimale. La classe doit aussi
permettre de calculer la valeur décimale qui correspond à la représentation binaire d'un float. Pourriez-vous
déterminer la perte de précision causée par la représentation.

Exercice 5 : Ecrire une classe FloatInfo qui permet de :

1. Déterminer les bornes des intervalles des floats représentés en:


 Faisant le calcul directement (utliser Math.pow());
 En utilisant les méthodes et constantes de la classe Float.
2. Déterminer le plus petit écart, le plus grand écart et un écart intérmédiaire entre deux floats consécutifs en:
 Faisant le calcul directement(Utiliser Math.pow());
 En utilisant les méthodes appropriées de la classe Math
3. Faire des opérations qui provoquent:
 un "positive overflow"
 Un "positive undeflow"
 Un "negative overflow"
 Un" negative underflow"
4. Montrer que l'entier 33554431 n'est pas correctement représenté en IEEE754 simple précision (float)
5. Déterminer le nombre de float qui se trouve entre deux puissances consécutives de 2. A votre avis, est ce
que ce nombre varie d'une puissance de 2 à l'autre ou reste le même? Justifier votre réponse

Exercice 6 : Ecrire une Classe RepresentationIEE754 à la manière dont est écrite la classe Math qui ne contient que
des méthodes statiques qui permettent d'obtenir les différentes informations sur le stockage interne des floats et
doubles.
API Java
Class Byte
public final class Byte
extends Number
implements Comparable<Byte>

The Byte class wraps a value of primitive type byte in an object. An object of type Byte contains a single field
whose type is byte

 Field Summary

Modifier and Type Field and Description

static byte MAX_VALUE

A constant holding the maximum value a byte can have, 27-1.


static byte MIN_VALUE

A constant holding the minimum value a byte can have, -2 .


7

Class Short
public final class Short
extends Number
implements Comparable<Short>

The Short class wraps a value of primitive type short in an object. An object of type Short contains a single
field whose type is short.

 Field Summary

Modifier and Type Field and Description

static short MAX_VALUE

A constant holding the maximum value a short can have , 215-1.


static short MIN_VALUE

A constant holding the minimum value a short can have , -215.

Class Integer
public final class Integer
extends Number
implements Comparable<Integer>
The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a
single field whose type is int.

 Field Summary

Modifier and Type Field and Description

static int MAX_VALUE

A constant holding the maximum value an int can have , 231-1.


static int MIN_VALUE

A constant holding the minimum value an int can have, -231.

 Method Summary

Modifier and Type Method and Description

static String toBinaryString(int i)

Returns a string representation of the integer argument as an unsigned integer in base 2.

static String toHexString(int i)

Returns a string representation of the integer argument as an unsigned integer in base 16.

static String toOctalString(int i)

Returns a string representation of the integer argument as an unsigned integer in base 8.

static String toString(int i, int radix)

Returns a string representation of the first argument in the radix specified by the second
argument.

Class Long
public final class Long
extends Number
implements Comparable<Long>

The Long class wraps a value of the primitive type long in an object. An object of type Long contains a single
field whose type is long.

 Field Summary

Modifier and Type Field and Description

static long MAX_VALUE


A constant holding the maximum value a long can have, 2 -1.63

static long MIN_VALUE

A constant holding the minimum value a long can have, -2 . 63

 Method Summary

Modifier and Type Method and Description

static String toBinaryString(long i)

Returns a string representation of the long argument as an unsigned integer in base 2.

static String toHexString(long i)

Returns a string representation of the long argument as an unsigned integer in base 16.

static String toOctalString(long i)

Returns a string representation of the long argument as an unsigned integer in base 8.

static String toString(long i, int radix)

Returns a string representation of the first argument in the radix specified by the second
argument.

static String toUnsignedString(long i, int radix)

Returns a string representation of the first argument as an unsigned integer value in the
radix specified by the second argument.

Class Float
public final class Float
extends Number
implements Comparable<Float>

The Float class wraps a value of primitive type float in an object. An object of type Float contains a single
field whose type is float.

 Field Summary

Modifier and Type Field and Description

static int MAX_EXPONENT

Maximum exponent a finite float variable may have.

static float MAX_VALUE

A constant holding the largest positive finite value of type float, (2-2-23)·2127.
static int MIN_EXPONENT

Minimum exponent a normalized float variable may have.

static float MIN_NORMAL

A constant holding the smallest positive normal value of type float ,2 .


-126

static float MIN_VALUE

A constant holding the smallest positive nonzero value of type float, 2 -149.

static float NaN

A constant holding a Not-a-Number (NaN) value of type float.

static float NEGATIVE_INFINITY

A constant holding the negative infinity of type float.

static float POSITIVE_INFINITY

A constant holding the positive infinity of type float.

 Method Summary

Modifier and Type Method and Description

static int floatToIntBits(float value)

Returns a representation of the specified floating-point value according to the IEEE 754
floating-point "single format" bit layout.

static int floatToRawIntBits(float value)

Returns a representation of the specified floating-point value according to the IEEE 754
floating-point "single format" bit layout, preserving Not-a-Number (NaN) values.

static float intBitsToFloat(int bits)

Returns the float value corresponding to a given bit representation.

static boolean isFinite(float f)

Returns true if the argument is a finite floating-point value; returns false otherwise
(for NaN and infinity arguments).

boolean isInfinite()

Returns true if this Float value is infinitely large in magnitude, false otherwise.

static boolean isInfinite(float v)

Returns true if the specified number is infinitely large in magnitude, false otherwise.
boolean isNaN()

Returns true if this Float value is a Not-a-Number (NaN), false otherwise.

static boolean isNaN(float v)

Returns true if the specified number is a Not-a-Number (NaN) value, false otherwise.

static String toHexString(float f)

Returns a hexadecimal string representation of the float argument.

String toString()

Returns a string representation of this Float object.

static String toString(float f)

Returns a string representation of the float argument.

static Float valueOf(float f)

Returns a Float instance representing the specified float value.

static Float valueOf(String s)

Returns a Float object holding the float value represented by the argument string s.

Class Double
public final class Double
extends Number
implements Comparable<Double>

The Double class wraps a value of the primitive type double in an object. An object of type Double contains a
single field whose type is double.

 Field Summary

Modifier and Type Field and Description

static int MAX_EXPONENT

Maximum exponent a finite double variable may have.

static double MAX_VALUE

A constant holding the largest positive finite value of type double, (2-2-52)·21023.

static int MIN_EXPONENT

Minimum exponent a normalized double variable may have.

static double MIN_NORMAL


A constant holding the smallest positive normal value of type double, 2-1022.
static double MIN_VALUE

A constant holding the smallest positive nonzero value of type double, 2-1074.

static double NaN

A constant holding a Not-a-Number (NaN) value of type double.

static double NEGATIVE_INFINITY

A constant holding the negative infinity of type double.

static double POSITIVE_INFINITY

A constant holding the positive infinity of type double.

 Method Summary

Modifier and Type Method and Description

static long doubleToLongBits(double value)

Returns a representation of the specified floating-point value according to the IEEE 754
floating-point "double format" bit layout.

static long doubleToRawLongBits(double value)

Returns a representation of the specified floating-point value according to the IEEE 754
floating-point "double format" bit layout, preserving Not-a-Number (NaN) values.

static boolean isFinite(double d)

Returns true if the argument is a finite floating-point value; returns false otherwise
(for NaN and infinity arguments).

boolean isInfinite()

Returns true if this Double value is infinitely large in magnitude, false otherwise.

static boolean isInfinite(double v)

Returns true if the specified number is infinitely large in magnitude, false otherwise.

boolean isNaN()

Returns true if this Double value is a Not-a-Number (NaN), false otherwise.

static boolean isNaN(double v)

Returns true if the specified number is a Not-a-Number (NaN) value, false otherwise.

static double longBitsToDouble(long bits)


Returns the double value corresponding to a given bit representation.

static String toHexString(double d)

Returns a hexadecimal string representation of the double argument.

Class Math
public final class Math
extends Object

The class Math contains methods for performing basic numeric operations such as the elementary exponential,
logarithm, square root, and trigonometric functions.

 Method Summary

Modifier and Type Method and Description

static int getExponent(double d)

Returns the unbiased exponent used in the representation of a double.

static int getExponent(float f)

Returns the unbiased exponent used in the representation of a float.

static double IEEEremainder(double f1, double f2)

Computes the remainder operation on two arguments as prescribed by the IEEE 754
standard.

static int incrementExact(int a)

Returns the argument incremented by one, throwing an exception if the result overflows
an int.

static long incrementExact(long a)

Returns the argument incremented by one, throwing an exception if the result overflows
a long.

static int multiplyExact(int x, int y)

Returns the product of the arguments, throwing an exception if the result overflows an int.

static long multiplyExact(long x, long y)

Returns the product of the arguments, throwing an exception if the result overflows
a long.

static int negateExact(int a)

Returns the negation of the argument, throwing an exception if the result overflows an int.
static long negateExact(long a)

Returns the negation of the argument, throwing an exception if the result overflows a long.

static double nextAfter(double start, double direction)

Returns the floating-point number adjacent to the first argument in the direction of the
second argument.

static float nextAfter(float start, double direction)

Returns the floating-point number adjacent to the first argument in the direction of the
second argument.

static double nextDown(double d)

Returns the floating-point value adjacent to d in the direction of negative infinity.

static float nextDown(float f)

Returns the floating-point value adjacent to f in the direction of negative infinity.

static double nextUp(double d)

Returns the floating-point value adjacent to d in the direction of positive infinity.

static float nextUp(float f)

Returns the floating-point value adjacent to f in the direction of positive infinity.

static double pow(double a, double b)

Returns the value of the first argument raised to the power of the second argument.

static int subtractExact(int x, int y)

Returns the difference of the arguments, throwing an exception if the result overflows
an int.

static long subtractExact(long x, long y)

Returns the difference of the arguments, throwing an exception if the result overflows
a long.

static double ulp(double d)

Returns the size of an ulp of the argument.

static float ulp(float f)

Returns the size of an ulp of the argument.

Vous aimerez peut-être aussi