Reputation: 153
I want to read 1 bit from a udp packet.
The udp packet looks like this (c code):
struct typedef struct s_foo
{
__u32 foo;
__u8 bar:1,
bob:1;
} __attribute__((packed)) s_foo;
How in java can i read this?
So far I have this but i can't read foo nor bar or bob...
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);
}
}
}
Upvotes: 1
Views: 387
Reputation: 8771
To test a bit you must use bitwise operators example :
This will test that value has the bit 0b00001000 set
boolean result = value & 0x0A;
This will return you the content of the bit 0b00001000
int value = value & ~0x0A;
Here is a link that will help you : http://vipan.com/htdocs/bitwisehelp.html
EDIT :
To read two bit at a time :
int nMask = 0x1A; // 0b00011000
nValue = nValue & nMask;
nValue = nValue >> 3;
nValue will contain bits at 0b00000011
Upvotes: 2