我想从udp数据包读取1位。
udp数据包看起来像这样(c代码):
struct typedef struct s_foo
{
__u32 foo;
__u8 bar:1,
bob:1;
} __attribute__((packed)) s_foo;
如何在java中读到这个?
到目前为止,我有这个,但我不能阅读foo,也不能阅读或删除......
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class BroadcastListener
{
public static void main(String[] args) throws IOException
{
if (args.length != 1) {
System.out.println("usage: <program> port");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
DatagramSocket dgram = new DatagramSocket(port);
byte[] buffer = new byte[2048];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while (true) {
dgram.receive(packet);
String msg = new String(buffer, 0, packet.getLength());
System.out.println(packet.getAddress().getHostName() + ": "
+ msg);
packet.setLength(buffer.length);
}
}
}
答案 0 :(得分:2)
要测试一下,必须使用按位运算符示例:
这将测试该值是否设置了位0b00001000
boolean result = value & 0x0A;
这将返回位0b00001000
的内容int value = value&amp; 〜的0x0A;
以下链接可以帮助您:http://vipan.com/htdocs/bitwisehelp.html
编辑:
一次读取两位:
int nMask = 0x1A; // 0b00011000
nValue = nValue & nMask;
nValue = nValue >> 3;
nValue will contain bits at 0b00000011