ASCII/Hex funciona mas, e o oposto?

3 respostas
ccostavictor

Achei isso aqui no forum:

public static String toHex(String text) { StringBuilder out = new StringBuilder(); char[] textChars = text.toCharArray(); for (int x = 0; x < textChars.length; x++) { out.append(Integer.toHexString(textChars[x]).toUpperCase()); } return out.toString(); }

Resolvi testar no NetBeans (é, já fiquei mal acostumado…):

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JFVisor.java
 *
 * Created on 21/01/2011, 09:55:41
 */

/**
 *
 * @author victorcosta
 */
public class JFVisor extends javax.swing.JFrame {


    /** Creates new form JFVisor */
    public JFVisor() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTHex = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jBTextoPHex = new javax.swing.JButton();
        jBLimpa = new javax.swing.JButton();
        jTTexto = new javax.swing.JTextField();
        jBHexPText = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBackground(new java.awt.Color(12, 12, 12));
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "HEX/ASCII", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 12), new java.awt.Color(254, 254, 254))); // NOI18N

        jLabel1.setText("Developed by http://nerdbaiano.blogspot.com");

        jLabel2.setText("Texto:");

        jLabel3.setText("Hex:");

        jBTextoPHex.setBackground(new java.awt.Color(50, 50, 50));
        jBTextoPHex.setForeground(new java.awt.Color(90, 90, 90));
        jBTextoPHex.setText("ASCII/Hex");
        jBTextoPHex.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBTextoPHexActionPerformed(evt);
            }
        });

        jBLimpa.setBackground(new java.awt.Color(50, 50, 50));
        jBLimpa.setForeground(new java.awt.Color(90, 90, 90));
        jBLimpa.setText("Limpar");
        jBLimpa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBLimpaActionPerformed(evt);
            }
        });

        jTTexto.setText("Cole o link invertido aqui.");

        jBHexPText.setBackground(new java.awt.Color(50, 50, 50));
        jBHexPText.setForeground(new java.awt.Color(90, 90, 90));
        jBHexPText.setText("Hex/ASCII");
        jBHexPText.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBHexPTextActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTHex, javax.swing.GroupLayout.DEFAULT_SIZE, 298, Short.MAX_VALUE)
                    .addComponent(jTTexto, javax.swing.GroupLayout.DEFAULT_SIZE, 298, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jBTextoPHex, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jBHexPText)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jBLimpa, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE))
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2))
                .addContainerGap())
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jBHexPText, jBTextoPHex});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTTexto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTHex, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jBTextoPHex)
                    .addComponent(jBLimpa)
                    .addComponent(jBHexPText))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>

    private void jBTextoPHexActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
        jTHex.setText(toHex(jTTexto.getText()));
    }                                          

    private void jBLimpaActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        jTHex.setText("");
        jTTexto.setText("");
    }                                       

    private void jBHexPTextActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }
     public static String toHex(String text) {
         StringBuilder out = new StringBuilder();
         char[] textChars = text.toCharArray();
         for (int x = 0; x < textChars.length; x++) {
             out.append(Integer.toHexString(textChars[x]).toUpperCase());
         }
         return out.toString();
     }
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JFVisor().setVisible(true);
            }
        });

    }

    // Variables declaration - do not modify
    private javax.swing.JButton jBHexPText;
    private javax.swing.JButton jBLimpa;
    private javax.swing.JButton jBTextoPHex;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField jTHex;
    private javax.swing.JTextField jTTexto;
    // End of variables declaration

}

Funcionou direitinho, mas gostaria de saber como fazer o jBTHexPText pegar o texto no jTHex e colocá-lo em texto normal na jTTexto…

[]'s

3 Respostas

pedroroxd
ccostavictor:
Funcionou direitinho, mas gostaria de saber como fazer o jBTHexPText pegar o texto no jTHex e colocá-lo em texto normal na jTTexto...
Só fazer isso:
public String convertHexToString (String hex) {
	  	  StringBuilder sb = new StringBuilder();
	 
		  for( int i=0; i<hex.length()-1; i+=2 ){
		      String output = hex.substring(i, (i + 2));
		      //converte hex para decimal
		      int decimal = Integer.parseInt(output, 16);
		      //converte decimal para char
		      sb.append((char)decimal);   
	  }
		  return sb.toString();	 
    }
Chama ele no click do jBHexPText:
jTTexto.setText(convertHexToString(jTHex.getText()));
ccostavictor:
Resolvi testar no NetBeans (é, já fiquei mal acostumado....)
Realmente... Aproveita enquanto ta novo pra ir tirando esses vícios... Quando você ver eclipse nunca mais vai querer olhar para netbeans... Aproveita pra ganhar tempo... Já começou na frente (ganhou o primeiro pc com 6 anos de idade...)
ccostavictor

pedroroxd, obrigado aew…
admito que não compreendi muito bem as strings de conversão…
até porque “for” sempre me causa confusão! Acho que isso pega-se com algum tempo.
Hahaha obrigado pela visita ao blog e, já que vc também usa Ubuntu vou testar o Eclipse agora mesmo… (apesar de que ficar usando IDEs enquanto sou um novato em java me dá uma baita dor de consciência)
[]'s

pedroroxd

ccostavictor:
pedroroxd, obrigado aew…
admito que não compreendi muito bem as strings de conversão…
até porque “for” sempre me causa confusão! Acho que isso pega-se com algum tempo.
Hahaha obrigado pela visita ao blog e, já que vc também usa Ubuntu vou testar o Eclipse agora mesmo… (apesar de que ficar usando IDEs enquanto sou um novato em java me dá uma baita dor de consciência)
[]'s

Hehe… fikei curioso, gostei do blog tb, rs…
No Ubuntu você usa o gerenciador de pacotes synaptic, e pesquisa Eclipse.
Quando você clica nele, ele instala tudo que é necessário em sua máquina… Bem mais simples

Criado 22 de janeiro de 2011
Ultima resposta 23 de jan. de 2011
Respostas 3
Participantes 2