Trabalhando com bits

6 respostas
vitor_lima

Bom dia à todos!

Estou tentando fazer um método que devolva o número de 1’s que um número tem na forma binária ou que devolva a quantidade de permutações de bits que são necessárias para se chegar de n1 em n2.

Por exemplo:

int qntUns (int num){



}

Se eu fizer
Chamada: Devolve:
qntUns (5) 2
qntUns (1) 1
qntUns (16) 1
qntUns (15) 4

Segunda altenativa:

int permutacoes (int n1, int n2){



}

Argumentos: Em binário Devolve
n1 = 3 n2 = 5 n1 = 00011 n2 = 00101 1 (pois só é necessário trocar o segundo um de n1 por qualquer zero para se chegar em n2)

Não sei se fui muito claro…

Mas é isso aí.

Se alguém tiver qualquer idéia, por favor, poste aqui.

Abraço.

6 Respostas

lina

Oi,

Dica:

String by = Integer.toBinaryString(50); System.out.println("Byte: " + byte);

Tchauzin!

JoaoBluSCBR

Usei a divisão por 2 consecutivamente para conseguir o valor em binario.

Tem o toBinaryString da classe Integer, mas sempre acho que para quem
está aprendendo, entender como funciona o processo é mais interessante.

public Teste(){
        int v = 43;
        String EmBinario = toBinaryString(v);
        char[] separado1 = separaBinario(EmBinario);
        int contaUns1 = contaUns(separado1) ;
        
        int v2 = 38;
        String EmBinario2 = toBinaryString(v2);
        char[] separado2 = separaBinario(EmBinario2);
        int contaUns2 = contaUns(separado2) ;
        
        int trocas = nrPermutacoes(separado1, separado2);
    }
    
    
    
    public String toBinaryString(int v){
        String retorno = "";
        while(true){
            int resto = v % 2;
            retorno = "" + resto + retorno;
            int quo = v/2;
            if(quo==1){
                retorno = "" + quo + retorno;
                break;
            } 
            v = quo;
        }
        return retorno;
    }
    
    public char[] separaBinario(String sBin){
        char[] sep = new char[8];
        int pos = 7;
        for(int i=sBin.length()-1; i>=0; i--){
            sep[pos] = sBin.charAt(i);
            pos--;
        }
        for(int i = pos; i>=0; i--){
            sep[i] = '0';
        }
        return sep;
    }
    
    public int contaUns(char[] bin){
        int ret = 0;
        for(int i=0; i<8; i++){
            if( bin[i] == '1')
                ret++;
        }
        return ret;
    }
    
    public int nrPermutacoes(char[] bin1, char[] bin2){
        int trocas = 0;
        for(int i=0; i<8; i++){
            //se uma posicao é diferente entao é uma troca que precisa ser feita.
            if(bin1[i]!=bin2[i])
                trocas++;
        }
        return trocas;
    }
vitor_lima

Pessoal, antes de mais nada, muito obrigado.

Então, eu já implementei uma solução parecida usando strings, mas isto é muito lento.

Estava pensando em fazer algo com shifts e com and ou or bit a bit.

Mas ainda não achei um jeito…

lina
JoaoBluSCBR:
Usei a divisão por 2 consecutivamente para conseguir o valor em binario.

Tem o toBinaryString da classe Integer, mas sempre acho que para quem
está aprendendo, entender como funciona o processo é mais interessante.

Oi,

Sem problemas... Eu só trocaria o seu método contaUns:

public int contaUns(String as_binario) {

   return (System.out.println(as_binario.replaceAll("[^1]*","").length()));

}

Tchauzin!

L

antes eu ficava brincando com bits e fiz um exemplo básico deles, mas não sei se vai servir pra vc, mesmo assim estou postando aqui

import javax.swing.JFormattedTextField;
import javax.swing.text.Document;


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

/*
 * bit.java
 *
 * Created on 25/11/2010, 09:20:36
 */

/**
 * 
 * @author vcarretero
 */
public class bit extends javax.swing.JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private int val1, val2;

	/** Creates new form bit */
	public bit() {
		super("Deslocamento de bits");
		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.
	 */
	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {

		jPanel1 = new javax.swing.JPanel();
		lblEntreBits = new javax.swing.JLabel();
		lblValor1 = new javax.swing.JLabel();
		lblValor2 = new javax.swing.JLabel();
		lblResultado = new javax.swing.JLabel();
		txtValor2 = new javax.swing.JFormattedTextField();
		txtValor1 = new javax.swing.JTextField();
		txtResultado = new javax.swing.JTextField();
		btnAND = new javax.swing.JButton();
		btnEXCLUSIVE = new javax.swing.JButton();
		btnNCLUIR = new javax.swing.JButton();
		btnCOMPLEMENTO = new javax.swing.JButton();
		txtValorResult1 = new javax.swing.JTextField();
		txtValorResult = new javax.swing.JTextField();
		txtValorResult2 = new javax.swing.JTextField();
		lblBitsRepre = new javax.swing.JLabel();
		btnLimpar = new javax.swing.JButton();

		java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit()
				.getScreenSize();
		setBounds((screenSize.width - 500) / 3, (screenSize.height - 500) / 3,
				500, 1000);
		setResizable(false);
		setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

		jPanel1.setBackground(new java.awt.Color(12, 3, 120));

		lblEntreBits.setFont(new java.awt.Font("Perpetua Titling MT", 1, 18)); // NOI18N
		lblEntreBits.setForeground(new java.awt.Color(255, 255, 255));
		lblEntreBits.setText("Entre com 2 bits");

		lblValor1.setFont(new java.awt.Font("Perpetua Titling MT", 1, 14)); // NOI18N
		lblValor1.setForeground(new java.awt.Color(255, 255, 255));
		lblValor1.setText("valor 1  :");

		lblValor2.setFont(new java.awt.Font("Perpetua Titling MT", 1, 14)); // NOI18N
		lblValor2.setForeground(new java.awt.Color(255, 255, 255));
		lblValor2.setText("valor 2  :");

		lblResultado.setFont(new java.awt.Font("Perpetua Titling MT", 1, 14)); // NOI18N
		lblResultado.setForeground(new java.awt.Color(255, 255, 255));
		lblResultado.setText("resultado :");

		txtValor2.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				txtValor2ActionPerformed(evt);
			}
		});

		txtValor1.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				txtValor1ActionPerformed(evt);
			}
		});

		txtResultado.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				txtResultadoActionPerformed(evt);
			}
		});

		btnAND.setForeground(new java.awt.Color(255, 166, 0));
		btnAND.setText("AND");
		btnAND.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnANDActionPerformed(evt);
				setFields();
				txtResultado.setText(Integer.toString(val1 & val2));
				txtValorResult.setText(getBits(val1 & val2));

			}

			// private String gettxtValorResult(int i) {
			// return null;
			// }
		});

		btnEXCLUSIVE.setForeground(new java.awt.Color(255, 166, 0));
		btnEXCLUSIVE.setText("Exclusive OR");
		btnEXCLUSIVE.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnEXCLUSIVEActionPerformed(evt);

				setFields();
				txtResultado.setText(Integer.toString(val1 ^ val2));
				txtValorResult.setText(getBits(val1 ^ val2));

			}

			// private String gettxtValorResult(int i) {
			// return null;
			// }
		});

		btnNCLUIR.setForeground(new java.awt.Color(255, 166, 0));
		btnNCLUIR.setText("Incluir OR");
		btnNCLUIR.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnNCLUIRActionPerformed(evt);

				setFields();
				txtResultado.setText(Integer.toString(val1 | val2));
				txtValorResult.setText(getBits(val1 | val2));

			}

			// private String gettxtValorResult(int i) {
			// return null;
			// }
		});

		btnCOMPLEMENTO.setForeground(new java.awt.Color(255, 166, 0));
		btnCOMPLEMENTO.setText("Complemento");
		btnCOMPLEMENTO.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnCOMPLEMENTOActionPerformed(evt);

				txtValor2.setText("");
				txtValorResult2.setText("");
				int val = Integer.parseInt(txtValor1.getText());
				txtResultado.setText(Integer.toString(~val));
				txtValorResult1.setText(getBits(val));
				txtValorResult.setText(getBits(~val));

			}
		});

		txtValorResult1.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				txtValorResult1ActionPerformed(evt);
			}
		});

		txtValorResult.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				txtValorResultActionPerformed(evt);
			}
		});

		txtValorResult2.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				txtValorResult2ActionPerformed(evt);
			}
		});

		lblBitsRepre.setFont(new java.awt.Font("Perpetua Titling MT", 1, 18)); // NOI18N
		lblBitsRepre.setForeground(new java.awt.Color(255, 255, 255));
		lblBitsRepre.setText("BITS Representados");

		btnLimpar.setForeground(new java.awt.Color(255, 166, 0));
		btnLimpar.setText("Limpar");
		btnLimpar.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnLimparActionPerformed(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)
														.addGroup(
																jPanel1Layout
																		.createSequentialGroup()
																		.addGroup(
																				jPanel1Layout
																						.createParallelGroup(
																								javax.swing.GroupLayout.Alignment.LEADING)
																						.addGroup(
																								jPanel1Layout
																										.createParallelGroup(
																												javax.swing.GroupLayout.Alignment.LEADING,
																												false)
																										.addGroup(
																												javax.swing.GroupLayout.Alignment.TRAILING,
																												jPanel1Layout
																														.createSequentialGroup()
																														.addComponent(
																																lblValor2)
																														.addPreferredGap(
																																javax.swing.LayoutStyle.ComponentPlacement.RELATED,
																																javax.swing.GroupLayout.DEFAULT_SIZE,
																																Short.MAX_VALUE)
																														.addComponent(
																																txtValor2,
																																javax.swing.GroupLayout.PREFERRED_SIZE,
																																100,
																																javax.swing.GroupLayout.PREFERRED_SIZE))
																										.addGroup(
																												javax.swing.GroupLayout.Alignment.TRAILING,
																												jPanel1Layout
																														.createSequentialGroup()
																														.addGroup(
																																jPanel1Layout
																																		.createParallelGroup(
																																				javax.swing.GroupLayout.Alignment.TRAILING,
																																				false)
																																		.addComponent(
																																				lblValor1,
																																				javax.swing.GroupLayout.Alignment.LEADING,
																																				javax.swing.GroupLayout.DEFAULT_SIZE,
																																				javax.swing.GroupLayout.DEFAULT_SIZE,
																																				Short.MAX_VALUE)
																																		.addComponent(
																																				lblResultado,
																																				javax.swing.GroupLayout.Alignment.LEADING,
																																				javax.swing.GroupLayout.DEFAULT_SIZE,
																																				javax.swing.GroupLayout.DEFAULT_SIZE,
																																				Short.MAX_VALUE))
																														.addPreferredGap(
																																javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																														.addGroup(
																																jPanel1Layout
																																		.createParallelGroup(
																																				javax.swing.GroupLayout.Alignment.TRAILING)
																																		.addComponent(
																																				txtResultado,
																																				javax.swing.GroupLayout.PREFERRED_SIZE,
																																				100,
																																				javax.swing.GroupLayout.PREFERRED_SIZE)
																																		.addComponent(
																																				txtValor1,
																																				javax.swing.GroupLayout.PREFERRED_SIZE,
																																				100,
																																				javax.swing.GroupLayout.PREFERRED_SIZE))))
																						.addComponent(
																								lblEntreBits,
																								javax.swing.GroupLayout.PREFERRED_SIZE,
																								188,
																								javax.swing.GroupLayout.PREFERRED_SIZE))
																		.addGap(
																				37,
																				37,
																				37)
																		.addGroup(
																				jPanel1Layout
																						.createParallelGroup(
																								javax.swing.GroupLayout.Alignment.LEADING)
																						.addComponent(
																								lblBitsRepre,
																								javax.swing.GroupLayout.PREFERRED_SIZE,
																								240,
																								javax.swing.GroupLayout.PREFERRED_SIZE)
																						.addGroup(
																								jPanel1Layout
																										.createParallelGroup(
																												javax.swing.GroupLayout.Alignment.TRAILING)
																										.addComponent(
																												txtValorResult2,
																												javax.swing.GroupLayout.PREFERRED_SIZE,
																												276,
																												javax.swing.GroupLayout.PREFERRED_SIZE)
																										.addComponent(
																												txtValorResult1,
																												javax.swing.GroupLayout.PREFERRED_SIZE,
																												276,
																												javax.swing.GroupLayout.PREFERRED_SIZE)
																										.addComponent(
																												txtValorResult,
																												javax.swing.GroupLayout.PREFERRED_SIZE,
																												276,
																												javax.swing.GroupLayout.PREFERRED_SIZE)))
																		.addContainerGap(
																				46,
																				Short.MAX_VALUE))
														.addGroup(
																jPanel1Layout
																		.createSequentialGroup()
																		.addComponent(
																				btnAND)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																		.addComponent(
																				btnNCLUIR)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																		.addComponent(
																				btnEXCLUSIVE,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				116,
																				javax.swing.GroupLayout.PREFERRED_SIZE)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																		.addComponent(
																				btnCOMPLEMENTO)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED,
																				87,
																				Short.MAX_VALUE)
																		.addComponent(
																				btnLimpar)
																		.addGap(
																				41,
																				41,
																				41)))));
		jPanel1Layout
				.setVerticalGroup(jPanel1Layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								jPanel1Layout
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												jPanel1Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.BASELINE)
														.addComponent(
																lblEntreBits,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																30,
																javax.swing.GroupLayout.PREFERRED_SIZE)
														.addComponent(
																lblBitsRepre,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																30,
																javax.swing.GroupLayout.PREFERRED_SIZE))
										.addGap(18, 18, 18)
										.addGroup(
												jPanel1Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.BASELINE)
														.addComponent(
																lblValor1,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																30,
																javax.swing.GroupLayout.PREFERRED_SIZE)
														.addComponent(
																txtValor1,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE)
														.addComponent(
																txtValorResult1,
																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(
																txtValor2,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE)
														.addComponent(
																lblValor2,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																31,
																javax.swing.GroupLayout.PREFERRED_SIZE)
														.addComponent(
																txtValorResult2,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE))
										.addGap(18, 18, 18)
										.addGroup(
												jPanel1Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING)
														.addComponent(
																lblResultado,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																26,
																javax.swing.GroupLayout.PREFERRED_SIZE)
														.addGroup(
																jPanel1Layout
																		.createParallelGroup(
																				javax.swing.GroupLayout.Alignment.BASELINE)
																		.addComponent(
																				txtResultado,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				javax.swing.GroupLayout.DEFAULT_SIZE,
																				javax.swing.GroupLayout.PREFERRED_SIZE)
																		.addComponent(
																				txtValorResult,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				javax.swing.GroupLayout.DEFAULT_SIZE,
																				javax.swing.GroupLayout.PREFERRED_SIZE)))
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED,
												81, Short.MAX_VALUE)
										.addGroup(
												jPanel1Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.BASELINE)
														.addComponent(btnAND)
														.addComponent(btnNCLUIR)
														.addComponent(
																btnEXCLUSIVE)
														.addComponent(
																btnCOMPLEMENTO)
														.addComponent(btnLimpar))
										.addGap(30, 30, 30)));

		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.DEFAULT_SIZE,
				javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE));

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

	private void setFields() {

		val1 = Integer.parseInt(txtValor1.getText());
		val2 = Integer.parseInt(txtValor2.getText());

		txtValorResult1.setText(getBits(val1));
		txtValorResult2.setText(getBits(val2));

	}

	private String getBits(int value) {

		int displayMask = 1 << 31;
		StringBuffer buf = new StringBuffer(35);

		for (int c = 1; c <= 32; c++) {
			buf.append((value & displayMask) == 0 ? '0' : '1');
			value <<= 1;

			if (c % 8 == 0)
				buf.append(' ');
		}
		return buf.toString();

	}

	private void btnLimparActionPerformed(final java.awt.event.ActionEvent evt) {

		txtResultado.setText(null);
		txtValor1.setText(null);
		txtValor2.setText(null);
		txtValorResult.setText(null);
		txtValorResult1.setText(null);
		txtValorResult2.setText(null);
	}

	private void txtValor2ActionPerformed(java.awt.event.ActionEvent evt) {

	}

	private void txtValor1ActionPerformed(java.awt.event.ActionEvent evt) {
	}

	private void txtResultadoActionPerformed(java.awt.event.ActionEvent evt) {
	}

	private void btnANDActionPerformed(java.awt.event.ActionEvent evt) {
	}

	private void btnNCLUIRActionPerformed(java.awt.event.ActionEvent evt) {
	}

	private void btnEXCLUSIVEActionPerformed(java.awt.event.ActionEvent evt) {
	}

	private void btnCOMPLEMENTOActionPerformed(java.awt.event.ActionEvent evt) {
	}

	private void txtValorResult1ActionPerformed(java.awt.event.ActionEvent evt) {
	}

	private void txtValorResult2ActionPerformed(java.awt.event.ActionEvent evt) {
	}

	private void txtValorResultActionPerformed(java.awt.event.ActionEvent evt) {
	}

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new bit().setVisible(true);
			}
		});
	}

	// Variables declaration - do not modify
	private javax.swing.JButton btnAND;
	private javax.swing.JButton btnLimpar;
	private javax.swing.JButton btnCOMPLEMENTO;
	private javax.swing.JButton btnEXCLUSIVE;
	private javax.swing.JButton btnNCLUIR;
	private javax.swing.JPanel jPanel1;
	private javax.swing.JLabel lblBitsRepre;
	private javax.swing.JLabel lblEntreBits;
	private javax.swing.JLabel lblResultado;
	private javax.swing.JLabel lblValor1;
	private javax.swing.JLabel lblValor2;
	private javax.swing.JTextField txtResultado;
	private javax.swing.JTextField txtValor1;
	private javax.swing.JTextField txtValor2;
	private javax.swing.JTextField txtValorResult;
	private javax.swing.JTextField txtValorResult1;
	private javax.swing.JTextField txtValorResult2;
	// End of variables declaration

}
ViniGodoy

Outra possibilidade é usar os operadores bitwise:

int x = 10;

for (int i =0; i < 32; i++) {
   int ultimoBit = x & 0x1;
   System.out.print(ultimoBit);
   x >> 1;
}
System.out.println();

Note que o valor binário será impresso do valor menos significativo ao mais significativo (ao contrário).
Mas se para você só interessa contar a quantidade de "uns", tanto faz.

Criado 30 de junho de 2011
Ultima resposta 30 de jun. de 2011
Respostas 6
Participantes 5