I want to cast an int
to a byte[]
in Java. Can this be done directly? I noticed I can do this by converting it to a string like so:
int num = 5;
String dataString = Integer.toString(num);
byte[] data = dataString.getBytes();
I was just curious if there was a direct method such as num.getBytes()
.
I'm doing this in the frame of reference of using the Java Xbee library. In the example they do the following:
private static final String DATA_TO_SEND = "Hello XBee World!";
public static void main(String[] args) {
XBeeDevice myDevice = new XBeeDevice(PORT, BAUD_RATE);
byte[] dataToSend = DATA_TO_SEND.getBytes();
try {
myDevice.open();
System.out.format("Sending broadcast data: '%s'", new String(dataToSend));
myDevice.sendBroadcastData(dataToSend);
System.out.println(" >> Success");
} catch (XBeeException e) {
System.out.println(" >> Error");
e.printStackTrace();
System.exit(1);
} finally {
myDevice.close();
}
}
If I had an int how should I send that data? The sendBroadcastData()
function takes byte[]
as an argument. The example I'm referring to above can be found here