I am a new bee in java, I am simulating ethernet frame for which I
need to create byte array of 0'and 1's. Ethernet frame has 56 bit
preamble of alternating 1's and 0's. I need to send this field and
other with similar format over the socket. Can any one help and explain
me how to create byte array for 1 and 0?
I understand how to declare array. I am famalier with int,long double
array but I am confused for byte array. How do I insert 10101010 for
first byte in byte array? If possible can you give some code?
Assuming you understand binary, decimal & hex encoding.
1. Don't need array to send 10101010101010101010110... for 56 bits (7
bytes):
Problem is that Java compiler won't let you set byte b = 0xAA. You can
have such a
byte, but can't initialize it with Hex. It would be nice, but tuff
luck. I'm sure Java compiler
guys thought they were helping me.
So, set byte = -86 which compiler will allow and byte = -86 dec =
10101010 binary
= 0xAA hex. All same thing in memory, thus:
byte b = -86;
for (int i = 0; i < 7; i++) Send(b);
2. Suppose you need to send arbitraty bit patterns in bytes. For all bit
patterns less than
128 you can just use hex, e.g. byte b = 0x3C; For all bit patterns with
msb = 1, you need
to find equivalent decimal negative representation. Or you could set
up a byte array
containing all the 256 bit patterns and use an int index which you can
set with hex.
a. byte[] b = { 0, // 0. Dec value for byte 0x00
= 0000 0000
. . . . . .
126, // 126. Dec Value for byte
0x7F = 0111 1111
-128, // 127. Dec Value for byte
0x80 = 1000 0000
-127, // 128. Dec Value for byte
0x81 = 1000 0001
. . . . . .
-1}; // 255. Dec Value for byte
0xFF = 1111 1111
b. Same array with less typing and less bytecode:
byte[] b = new byte[256];
byte bPos = 0;
byte bNeg = -128;
for ( int i = 0; i <= 0x7F; i++) b
= bPos++;
for ( int i = 0x80; i <= 0xFF; i++) b = bNeg++;
Now, with our 256-byte byte array set we can send an abritray bit pattern
and use Hex.
Suppose we want to send 16 bits: 1000 1111 0001 0000 (i.e. 0x8F, 0x10).
Create an
int array for the 2-byte field/frame or whatever you wanna call it as:
int[] iField = {0x8F, 0x10};
for (int i = 0; i < iField.length; i++) Send(b[iField]);
where integers that the compiler will let us set the way we want are used
as indexes into
the 256-byte array.
Wanna print out a byte? Working with bits, a hex printout works well,
so:
int iHex = b[...some index we want...] & 0x00FF; //0x00FF clears any
sign extension
String s = Integer.toHexString(iHex);
--tex