incr.html 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. <html>
  2. <head>
  3. <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  4. <title>Incrementador em código de Gray</title>
  5. </head>
  6. <body bgcolor="FFFFFF">
  7. <h1>Incrementador em código de Gray</h1>
  8. <p> Cada componente incluído em uma biblioteca é definido através da criação de
  9. uma subclasse de <code> InstanceFactory </code> encontrada no pacote
  10. <code> com.cburch.logisim.instance</code>. Esta subclasse tem todo
  11. o código necessário.
  12. </p>
  13. <p> (Aqui descreveremos a API para a versão atual do Logisim.
  14. Você poderá encontrar algumas bibliotecas desenvolvidas para versões anteriores
  15. do Logisim, para componentes que foram desenvolvidos através da definição de duas
  16. classes, uma extensão <code> Component </code> e outra que estende
  17. <code> ComponentFactory</code>.
  18. Versão 2.3.0 introduziu uma API muito mais simples a <code> InstanceFactory</code>,
  19. a técnica anterior está obsoleta.)
  20. </p>
  21. <p> Três pacotes do Logisim resumem a maioria das classes relevantes para a definição
  22. bibliotecas de componentes.
  23. </p>
  24. <dl>
  25. <dt> <code> com.cburch.logisim.instance </code> </dt>
  26. <dd> <p> Contém classes especificamente relacionadas com a definição de componentes,
  27. incluindo as classes <code> InstanceFactory</code>, <code> InstanceState</code>,
  28. <code> InstancePainter</code> e <code> Instance</code>.
  29. </p> </dd>
  30. <dt> <code> com.cburch.logisim.data </code> </dt>
  31. <dd> <p> Contém classes relacionadas com os elementos de dados associados aos
  32. componentes, como a classe <code> Bounds </code> para representar retângulos limítrofes,
  33. ou a classe <code> Value </code> para representar os valores que possam
  34. existir em uma conexão.
  35. </p> </dd>
  36. <dt> <code> com.cburch.logisim.tools </code> </dt>
  37. <dd> <p> Contém classes relacionadas com a definição da biblioteca.
  38. </p> </dd>
  39. </dl>
  40. <h2> Acerca dos códigos de Gray </h2>
  41. <p> Antes de prosseguir, descreverei brevemente o código Gray em que estes
  42. exemplos se baseiam. Não é realmente importante para se entender como esses
  43. exemplos funcionam, assim você poderá pular para o código abaixo, se desejar -
  44. especialmente se você já conhecer os códigos de Gray.
  45. </p>
  46. <p> O código de Gray é uma técnica (em homenagem a Frank Gray) para iterar
  47. <var> n </var> sequências de bits com apenas uma ligeira modificação em cada etapa.
  48. Como exemplo, considere os 4 bits do código de Gray listados abaixo. </p>
  49. <blockquote><table><tbody>
  50. <tr><td valign="top">000<u>0</u>
  51. <br>00<u>0</u>1
  52. <br>001<u>1</u>
  53. <br>0<u>0</u>10
  54. </td><td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  55. </td><td valign="top">011<u>0</u>
  56. <br>01<u>1</u>1
  57. <br>010<u>1</u>
  58. <br><u>0</u>100
  59. </td><td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  60. </td><td valign="top">110<u>0</u>
  61. <br>11<u>0</u>1
  62. <br>111<u>1</u>
  63. <br>1<u>1</u>10
  64. </td><td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  65. </td><td valign="top">101<u>0</u>
  66. <br>10<u>1</u>1
  67. <br>100<u>1</u>
  68. <br><u>1</u>000
  69. </td></tr></tbody></table></blockquote>
  70. <p> Cada valor tem o bit sublinhado que irá mudar no próximo valor da
  71. sequência. Por exemplo, depois de 0000 virá 0001, no qual o bit final foi
  72. alterado, por isso o último bit será sublinhado.
  73. </p>
  74. <p> Os componentes predefinidos do Logisim não incluem recurso para se trabalhar
  75. com códigos de Gray.
  76. Porém, os projetistas eletrônicos consideram os códigos de Gray úteis às vezes. Um
  77. exemplo de aplicação particularmente notável dos códigos de Gray é sobre os eixos em
  78. mapas de Karnaugh.
  79. </p>
  80. <h2> GrayIncrementer </h2>
  81. <p> Este é um pequeno exemplo que ilustra os elementos essenciais para se definir
  82. um componente. Esse componente em particular é um incrementador,
  83. que tem uma entrada multibit e produz o código de Gray imediatamente seguinte a ele
  84. em sequência.
  85. </p>
  86. <pre>
  87. package com.cburch.gray;
  88. import com.cburch.logisim.data.Attribute;
  89. import com.cburch.logisim.data.BitWidth;
  90. import com.cburch.logisim.data.Bounds;
  91. import com.cburch.logisim.data.Value;
  92. import com.cburch.logisim.instance.InstanceFactory;
  93. import com.cburch.logisim.instance.InstancePainter;
  94. import com.cburch.logisim.instance.InstanceState;
  95. import com.cburch.logisim.instance.Port;
  96. import com.cburch.logisim.instance.StdAttr;
  97. /** This component takes a multibit input and outputs the value that follows it
  98. * in Gray Code. For instance, given input 0100 the output is 1100. */
  99. class GrayIncrementer extends InstanceFactory {
  100. /* Note that there are no instance variables. There is only one instance of
  101. * this class created, which manages all instances of the component. Any
  102. * information associated with individual instances should be handled
  103. * through attributes. For GrayIncrementer, each instance has a "bit width"
  104. * that it works with, and so we'll have an attribute. */
  105. /** The constructor configures the factory. */
  106. GrayIncrementer() {
  107. super("Gray Code Incrementer");
  108. /* This is how we can set up the attributes for GrayIncrementers. In
  109. * this case, there is just one attribute - the width - whose default
  110. * is 4. The StdAttr class defines several commonly occurring
  111. * attributes, including one for "bit width." It's best to use those
  112. * StdAttr attributes when appropriate: A user can then select several
  113. * components (even from differing factories) with the same attribute
  114. * and modify them all at once. */
  115. setAttributes(new Attribute[] { StdAttr.WIDTH },
  116. new Object[] { BitWidth.create(4) });
  117. /* The "offset bounds" is the location of the bounding rectangle
  118. * relative to the mouse location. Here, we're choosing the component to
  119. * be 30x30, and we're anchoring it relative to its primary output
  120. * (as is typical for Logisim), which happens to be in the center of the
  121. * east edge. Thus, the top left corner of the bounding box is 30 pixels
  122. * west and 15 pixels north of the mouse location. */
  123. setOffsetBounds(Bounds.create(-30, -15, 30, 30));
  124. /* The ports are locations where wires can be connected to this
  125. * component. Each port object says where to find the port relative to
  126. * the component's anchor location, then whether the port is an
  127. * input/output/both, and finally the expected bit width for the port.
  128. * The bit width can be a constant (like 1) or an attribute (as here).
  129. */
  130. setPorts(new Port[] {
  131. new Port(-30, 0, Port.INPUT, StdAttr.WIDTH),
  132. new Port(0, 0, Port.OUTPUT, StdAttr.WIDTH),
  133. });
  134. }
  135. /** Computes the current output for this component. This method is invoked
  136. * any time any of the inputs change their values; it may also be invoked in
  137. * other circumstances, even if there is no reason to expect it to change
  138. * anything. */
  139. public void propagate(InstanceState state) {
  140. // First we retrieve the value being fed into the input. Note that in
  141. // the setPorts invocation above, the component's input was included at
  142. // index 0 in the parameter array, so we use 0 as the parameter below.
  143. Value in = state.getPort(0);
  144. // Now compute the output. We've farmed this out to a helper method,
  145. // since the same logic is needed for the library's other components.
  146. Value out = nextGray(in);
  147. // Finally we propagate the output into the circuit. The first parameter
  148. // is 1 because in our list of ports (configured by invocation of
  149. // setPorts above) the output is at index 1. The second parameter is the
  150. // value we want to send on that port. And the last parameter is its
  151. // "delay" - the number of steps it will take for the output to update
  152. // after its input.
  153. state.setPort(1, out, out.getWidth() + 1);
  154. }
  155. /** Says how an individual instance should appear on the canvas. */
  156. public void paintInstance(InstancePainter painter) {
  157. // As it happens, InstancePainter contains several convenience methods
  158. // for drawing, and we'll use those here. Frequently, you'd want to
  159. // retrieve its Graphics object (painter.getGraphics) so you can draw
  160. // directly onto the canvas.
  161. painter.drawRectangle(painter.getBounds(), "G+1");
  162. painter.drawPorts();
  163. }
  164. /** Computes the next gray value in the sequence after prev. This static
  165. * method just does some bit twiddling; it doesn't have much to do with
  166. * Logisim except that it manipulates Value and BitWidth objects. */
  167. static Value nextGray(Value prev) {
  168. BitWidth bits = prev.getBitWidth();
  169. if(!prev.isFullyDefined()) return Value.createError(bits);
  170. int x = prev.toIntValue();
  171. int ct = (x >> 16) ^ x; // compute parity of x
  172. ct = (ct >> 8) ^ ct;
  173. ct = (ct >> 4) ^ ct;
  174. ct = (ct >> 2) ^ ct;
  175. ct = (ct >> 1) ^ ct;
  176. if((ct & 1) == 0) { // if parity is even, flip 1's bit
  177. x = x ^ 1;
  178. } else { // else flip bit just above last 1
  179. int y = x ^ (x & (x - 1)); // first compute the last 1
  180. y = (y << 1) & bits.getMask();
  181. x = (y == 0 ? 0 : x ^ y);
  182. }
  183. return Value.createKnown(bits, x);
  184. }
  185. }
  186. </pre>
  187. <p> Este exemplo, por si só não é suficiente para se criar um arquivo JAR funcional;
  188. você também deverá prover uma classe Library, conforme ilustrado na página a seguir.
  189. </p>
  190. <p><strong>Próximo:</strong> <a href="library.html">Biblioteca de Classe</a>.</p>
  191. </body>
  192. </html>