gpt4 book ai didi

Java:按位AND创建无符号字节

转载 作者:行者123 更新时间:2023-11-29 05:47:19 26 4
gpt4 key购买 nike

我想创建一个位数组,它将通过串行 RS232 发送到 Arduino 以控制输出引脚。

我通过创建复选框来实现这一点,选中这些复选框后会发送一个字节,其中每一位都代表一个引脚(打开或关闭)。

我已经使用按位 AND 运算实现了前 8 个复选框的代码,并打印到系统输出以确认我获得了正确的位模式。

它适用于前 7 个复选框,但第 8 个复选框不起作用,因为 java 字节已签名并且不允许我将“255”分配给字节值。有解决办法吗?

重要的代码是这一点:

    private void createOutputChars(){
byte outputByte1 = 0;
byte testByte = 1;
for (int x = 0;x < 8;x++){
if (digitalPinOutputArray[x].isSelected()) {
outputByte1 += (byte) (testByte);
}
testByte = (byte) (testByte << 1);
}

printByteArray(outputByte1);

}


private void printByteArray(int inputByte) {
// print out 1 or 0
byte comparison = 0x1;
for (int x = 0;x < 8;x++)
{
if ((inputByte & comparison) > 0) {
System.out.print("1");
}
else {System.out.print("0");}
comparison = (byte) (comparison << 1);
}
System.out.println();
}

完整的可编译 Java 代码是这样的:

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


import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ArduinoGUI extends javax.swing.JFrame {

/**
* Creates new form ArduinoGUI
*/
public ArduinoGUI() {
initCustomComponents();
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() {

buttonGroup1 = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
digitalPinPanel = new javax.swing.JPanel(new GridLayout(0, 3));
jPanel3 = new javax.swing.JPanel(new GridLayout(0, 1));
jPanel2 = new javax.swing.JPanel();
jProgressBar1 = new javax.swing.JProgressBar();
jProgressBar2 = new javax.swing.JProgressBar();
jProgressBar3 = new javax.swing.JProgressBar();
jProgressBar4 = new javax.swing.JProgressBar();
jProgressBar5 = new javax.swing.JProgressBar();
jProgressBar6 = new javax.swing.JProgressBar();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jProgressBar7 = new javax.swing.JProgressBar();
jProgressBar8 = new javax.swing.JProgressBar();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Outputs"));
jPanel1.setName("Outputs"); // NOI18N

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 209, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 106, Short.MAX_VALUE)
);

digitalPinPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Digital Pin State"));
digitalPinPanel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
digitalPinPanelMouseReleased(evt);
}
});
digitalPinLabelArray = new javax.swing.JLabel[digitalPinTotal];
digitalPinRadioButtonArray = new javax.swing.JRadioButton[digitalPinTotal][2];
digitalPinGroupArray = new javax.swing.ButtonGroup[digitalPinTotal];
for(int x = 0; x < digitalPinTotal ; x++) {
digitalPinGroupArray[x] = new javax.swing.ButtonGroup(); // populate button group
digitalPinLabelArray[x] = new javax.swing.JLabel(); // populate label array
digitalPinLabelArray[x].setText("Pin " + (x +2));
digitalPinPanel.add(digitalPinLabelArray[x]); // add label to panel
for(int y = 0; y < 2; y++){
digitalPinRadioButtonArray[x][y] = new javax.swing.JRadioButton(); // populate radio button array
digitalPinRadioButtonArray[x][y].addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("You clicked the button");
checkOnOutputs();
}
}
);

if (y == 0) {digitalPinRadioButtonArray[x][y].setText("Input");}
if (y == 1) {digitalPinRadioButtonArray[x][y].setText("Output"); digitalPinRadioButtonArray[x][y].setSelected(true);
}

digitalPinGroupArray[x].add(digitalPinRadioButtonArray[x][y]); // assign radio buttons to group
digitalPinPanel.add(digitalPinRadioButtonArray[x][y]); // add buttons to panel
}

}

jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Generated Boxes"));
digitalPinOutputArray = new javax.swing.JCheckBox[digitalPinTotal];

for(int x = 0; x < digitalPinTotal ; x++) {
digitalPinOutputArray[x] = new javax.swing.JCheckBox();
digitalPinOutputArray[x].setText("Output Pin " + (x+2));
digitalPinOutputArray[x].addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
createOutputChars();
}
});
jPanel3.add(digitalPinOutputArray[x]);

}

jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Analog Pin State"));

jProgressBar1.setMaximum(1024);
jProgressBar1.setToolTipText("");
jProgressBar1.setString(Integer.toString(jProgressBar1.getValue()));
jProgressBar1.setStringPainted(true);

jProgressBar2.setMaximum(1024);
jProgressBar2.setString(Integer.toString(jProgressBar2.getValue()));
jProgressBar2.setStringPainted(true);

jProgressBar3.setMaximum(1024);
jProgressBar3.setString(Integer.toString(jProgressBar3.getValue()));
jProgressBar3.setStringPainted(true);

jProgressBar4.setMaximum(1024);
jProgressBar4.setString(Integer.toString(jProgressBar4.getValue()));
jProgressBar4.setStringPainted(true);

jProgressBar5.setMaximum(1024);
jProgressBar5.setString(Integer.toString(jProgressBar5.getValue()));
jProgressBar5.setStringPainted(true);

jProgressBar6.setMaximum(1024);
jProgressBar6.setString(Integer.toString(jProgressBar6.getValue()));
jProgressBar6.setStringPainted(true);

jLabel1.setText("Pin A0");

jLabel2.setText("Pin A1");

jLabel3.setText("Pin A6");

jLabel4.setText("Pin A7");

jLabel5.setText("Pin A3");

jLabel6.setText("Pin A2");

jLabel7.setText("Pin A4");

jLabel8.setText("Pin A5");

jProgressBar7.setMaximum(1024);
jProgressBar7.setToolTipText("");
jProgressBar7.setString(Integer.toString(jProgressBar7.getValue()));
jProgressBar7.setStringPainted(true);

jProgressBar8.setMaximum(1024);
jProgressBar8.setToolTipText("");
jProgressBar8.setString(Integer.toString(jProgressBar8.getValue()));
jProgressBar8.setStringPainted(true);

javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jProgressBar5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jProgressBar6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jProgressBar2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel8)
.addComponent(jLabel5)
.addComponent(jLabel3)
.addComponent(jProgressBar7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jProgressBar3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(18, Short.MAX_VALUE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addComponent(jProgressBar4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4)
.addComponent(jProgressBar8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE))))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(4, 4, 4)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jProgressBar2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jProgressBar3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jProgressBar4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel7)
.addGap(9, 9, 9)
.addComponent(jProgressBar5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jProgressBar6, 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(jProgressBar7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jProgressBar8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(65, Short.MAX_VALUE))
);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addComponent(digitalPinPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(306, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(digitalPinPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap())
);

digitalPinPanel.getAccessibleContext().setAccessibleName("");

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

private void digitalPinPanelMouseReleased(java.awt.event.MouseEvent evt) {



}

private void checkOnOutputs() {
// if output selected enable checkbox otherwise disable it
for (int x = 0; x < digitalPinTotal; x++) {

if (digitalPinRadioButtonArray[x][0].isSelected() == true) {
digitalPinOutputArray[x].setEnabled(false);
}

if (digitalPinRadioButtonArray[x][1].isSelected() == true) {
digitalPinOutputArray[x].setEnabled(true);
}

}
}


/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ArduinoGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JPanel digitalPinPanel;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JProgressBar jProgressBar1;
private javax.swing.JProgressBar jProgressBar2;
private javax.swing.JProgressBar jProgressBar3;
private javax.swing.JProgressBar jProgressBar4;
private javax.swing.JProgressBar jProgressBar5;
private javax.swing.JProgressBar jProgressBar6;
private javax.swing.JProgressBar jProgressBar7;
private javax.swing.JProgressBar jProgressBar8;
// End of variables declaration
private int digitalPinTotal = 12;
private int analogPinTotal = 8;
private javax.swing.JCheckBox[] digitalPinOutputArray;
private javax.swing.JRadioButton[][] digitalPinRadioButtonArray;
private javax.swing.ButtonGroup[] digitalPinGroupArray;
private javax.swing.JLabel[] digitalPinLabelArray;

private void initCustomComponents() {
//throw new UnsupportedOperationException("Not yet implemented");
// create checkbox array
}

private void createOutputChars(){
byte outputByte1 = 0;
byte testByte = 1;
for (int x = 0;x < 8;x++){
if (digitalPinOutputArray[x].isSelected()) {
outputByte1 += (byte) (testByte);
}
testByte = (byte) (testByte << 1);
}

printByteArray(outputByte1);

}


private void printByteArray(int inputByte) {
// print out 1 or 0
byte comparison = 0x1;
for (int x = 0;x < 8;x++)
{
if ((inputByte & comparison) > 0) {
System.out.print("1");
}
else {System.out.print("0");}
comparison = (byte) (comparison << 1);
}
System.out.println();
}

最佳答案

干脆忽略java byte是有符号的。它只会对少数操作产生影响(最显着的是关系运算符,如 >)。

按位运算符(|、&、^)提供与字节无符号时相同的位模式结果。

我会只将要控制的位数存储到组合框并像这样设置/读取位:

public static boolean isBitSet(byte b, int bitNo) {
return (b & (1 << bitNo) != 0;
}

public static byte setBit(byte b, int bitNo) {
return (byte) (b | (1 << bitNo));
}

public static byte clearBit(byte b, int bitNo) {
return (byte) (b & (~(1 << bitNo)));
}

虽然直接将 C 代码移植到 java 通常会由于缺少无符号类型而导致不同的行为,但差异并不是那么大。所有无符号类型都可以替换为有符号类型,这只需要一些注意(和知识),因为某些操作需要以不同的方式表达。

顺便说一句:没有人会耐心地挖掘 UI 构建器生成的代码墙。如果您有具体问题,请提供一个简短示例,最好是可编译和可执行的。

关于Java:按位AND创建无符号字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15390129/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com