在 Java 中如何获得表示 unsigned int 的字节?
我有从 0 到 255 的整数,我需要将它们传递到编码为无符号字节的 OutputStream。我尝试使用像这样的掩码进行转换,但如果 i=1,我的流的另一端(需要 uint8_t 的串行设备)认为我已经发送了一个无符号整数 = 6。
OutputStream out;
public void writeToStream(int i) throws Exception {
out.write(((byte)(i & 0xff)));
}
我正在与 Arduino 交谈/dev/ttyUSB0
使用 Ubuntu,如果这让事情或多或少变得有趣的话。
这是 Arduino 代码:
uint8_t nextByte() {
while(1) {
if(Serial.available() > 0) {
uint8_t b = Serial.read();
return b;
}
}
}
我还有一些与 Arduino 代码配合得很好的 Python 代码,如果我在 Python 中使用此代码,Arduino 会很高兴地收到正确的整数:
class writerThread(threading.Thread):
def __init__(self, threadID, name):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
def run(self):
while True:
input = raw_input("[W}Give Me Input!")
if (input == "exit"):
exit("Goodbye");
print ("[W]You input %s\n" % input.strip())
fval = [ int(input.strip()) ]
ser.write("".join([chr(x) for x in fval]))
我最终也想在 Scala 中执行此操作,但我'在解决这个问题时,我回到了 Java 以避免复杂性。
I have integers from 0 to 255, and I need to pass them along to an OutputStream encoded as unsigned bytes. I've tried to convert using a mask like so, but if i=1, the other end of my stream (a serial device expecting uint8_t) thinks I've sent an unsigned integer = 6.
OutputStream out;
public void writeToStream(int i) throws Exception {
out.write(((byte)(i & 0xff)));
}
I'm talking to an Arduino at /dev/ttyUSB0
using Ubuntu if this makes things any more or less interesting.
Here's the Arduino code:
uint8_t nextByte() {
while(1) {
if(Serial.available() > 0) {
uint8_t b = Serial.read();
return b;
}
}
}
I also have some Python code that works great with the Arduino code, and the Arduino happily receives the correct integer if I use this code in Python:
class writerThread(threading.Thread):
def __init__(self, threadID, name):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
def run(self):
while True:
input = raw_input("[W}Give Me Input!")
if (input == "exit"):
exit("Goodbye");
print ("[W]You input %s\n" % input.strip())
fval = [ int(input.strip()) ]
ser.write("".join([chr(x) for x in fval]))
I'd also eventually like to do this in Scala, but I'm falling back to Java to avoid the complexity while I solve this issue.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想你只是想在这里
out.write(i)
。仅从 int 参数i
写入低八位。I think you just want
out.write(i)
here. Only the eight low-order bits are written from the int argumenti
.转换,然后掩码:
((byte)(i)&0xff)
但是,有些事情很奇怪,因为:
(dec)8 - (binary)1000
(十进制)6 - (二进制)0110
[编辑]
当您发送 1(二进制)0001 时,您的 Arduino 如何接收 6(二进制)0110?
[/编辑]
Cast, then mask:
((byte)(i)&0xff)
But, something is very strange since:
(dec)8 - (binary)1000
(dec)6 - (binary)0110
[edit]
How is your Arduino receiving 6 (binary)0110 when you send 1 (binary)0001?
[/edit]