I am new to java. I receive the UDP data in byte array. Each elements of the byte array have the hexadecimal value. I need to convert each element to integer.
How to convert it to integer?
sample code:
public int[] bytearray2intarray(byte[] barray)
{
int[] iarray = new int[barray.length];
int i = 0;
for (byte b : barray)
iarray[i++] = b & 0xff;
// "and" with 0xff since bytes are signed in java
return iarray;
}
Manually: Iterate over the elements of the array and cast them to int or use Integer.valueOf() to create integer objects.
Function : return unsigned value of byte array.
public static long bytesToDec(byte[] byteArray) {
long total = 0;
for(int i = 0 ; i < byteArray.length ; i++) {
int temp = byteArray[i];
if(temp < 0) {
total += (128 + (byteArray[i] & 0x7f)) * Math.pow(2, (byteArray-1-i)*8);
} else {
total += ((byteArray[i] & 0x7f) * Math.pow(2, (byteArray-1-i)*8));
}
}
return total;
}
Here's something I found that may be of use to you http://blog.codebeach.com/2008/02/convert-hex-string-to-integer-and-back.html
Related
How can i iterate bits in a byte array?
You'd have to write your own implementation of Iterable<Boolean> which took an array of bytes, and then created Iterator<Boolean> values which remembered the current index into the byte array and the current index within the current byte. Then a utility method like this would come in handy:
private static Boolean isBitSet(byte b, int bit)
{
return (b & (1 << bit)) != 0;
}
(where bit ranges from 0 to 7). Each time next() was called you'd have to increment your bit index within the current byte, and increment the byte index within byte array if you reached "the 9th bit".
It's not really hard - but a bit of a pain. Let me know if you'd like a sample implementation...
public class ByteArrayBitIterable implements Iterable<Boolean> {
private final byte[] array;
public ByteArrayBitIterable(byte[] array) {
this.array = array;
}
public Iterator<Boolean> iterator() {
return new Iterator<Boolean>() {
private int bitIndex = 0;
private int arrayIndex = 0;
public boolean hasNext() {
return (arrayIndex < array.length) && (bitIndex < 8);
}
public Boolean next() {
Boolean val = (array[arrayIndex] >> (7 - bitIndex) & 1) == 1;
bitIndex++;
if (bitIndex == 8) {
bitIndex = 0;
arrayIndex++;
}
return val;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public static void main(String[] a) {
ByteArrayBitIterable test = new ByteArrayBitIterable(
new byte[]{(byte)0xAA, (byte)0xAA});
for (boolean b : test)
System.out.println(b);
}
}
Original:
for (int i = 0; i < byteArray.Length; i++)
{
byte b = byteArray[i];
byte mask = 0x01;
for (int j = 0; j < 8; j++)
{
bool value = b & mask;
mask << 1;
}
}
Or using Java idioms
for (byte b : byteArray ) {
for ( int mask = 0x01; mask != 0x100; mask <<= 1 ) {
boolean value = ( b & mask ) != 0;
}
}
An alternative would be to use a BitInputStream like the one you can find here and write code like this:
BitInputStream bin = new BitInputStream(new ByteArrayInputStream(bytes));
while(true){
int bit = bin.readBit();
// do something
}
bin.close();
(Note: Code doesn't contain EOFException or IOException handling for brevity.)
But I'd go with Jon Skeets variant and do it on my own.
I needed some bit streaming in my application. Here you can find my BitArray implementation. It is not a real iterator pattern but you can ask for 1-32 bits from the array in a streaming way. There is also an alternate implementation called BitReader later in the file.
I know, probably not the "coolest" way to do it, but you can extract each bit with the following code.
int n = 156;
String bin = Integer.toBinaryString(n);
System.out.println(bin);
char arr[] = bin.toCharArray();
for(int i = 0; i < arr.length; ++i) {
System.out.println("Bit number " + (i + 1) + " = " + arr[i]);
}
10011100
Bit number 1 = 1
Bit number 2 = 0
Bit number 3 = 0
Bit number 4 = 1
Bit number 5 = 1
Bit number 6 = 1
Bit number 7 = 0
Bit number 8 = 0
You can iterate through the byte array, and for each byte use the bitwise operators to iterate though its bits.
Alternatively, you can use BitSet for this:
byte[] bytes=...;
BitSet bitSet=BitSet.valueOf(bytes);
for(int i=0;i<bitSet.length();i++){
boolean bit=bitSet.get(i);
//use your bit
}
I have a BitSet, which needs to be converted to a Byte[]. However, by using BitSet.toByteArray(), I don't get the correct output. I have tried converting the Byte[] to its binary form in order to check whether the Bitset and the binary form of the Byte[] are similiar.
public static void generate() {
BitSet temp1 = new BitSet(64);
for (int i = 0; i < 64; i++) {
if(i % 8 != 0 && i < 23) {
temp1.set(i, true);
}
}
StringBuilder s = new StringBuilder();
for (int i = 0; i < 64; i++) {
s.append(temp1.get(i) == true ? 1 : 0);
}
System.out.println(s);
byte[] tempByteKey1 = temp1.toByteArray();
for (byte b : tempByteKey1) {
System.out.print(Integer.toBinaryString(b & 255 | 256).substring(1));
}
}
Output:
Bitset: 0111111101111111011111100000000000000000000000000000000000000000
Converted Byte: 1111111011111110011111100000000000000000000000000000000000000000
They are both 64 bits, but the first 0 in the BitSet is placed somewhere else after the conversion. Why is this happening, and how can I fix it?
From BitSet#toByteArray() javadoc:
Returns a new byte array containing all the bits in this bit set.
More precisely, if..
byte[] bytes = s.toByteArray();
then
bytes.length == (s.length()+7)/8
and
s.get(n) == ((bytes[n/8] & (1<<(n%8))) != 0)
for all n < 8 * bytes.length.
#return a byte array containing a little-endian representation of all the bits in this bit set
#since 1.7
Attention: toByteArray() doesn't even claim to know size(), it is only "reliable" regarding length()!
..So I would propose as implementation (alternative for your toBinaryString()) a method like:
static String toBinaryString(byte[] barr, int size) {
StringBuilder sb = new StringBuilder();
int i = 0;
for (; i < 8 * barr.length; i++) {
sb.append(((barr[i / 8] & (1 << (i % 8))) != 0) ? '1' : '0');
}
for (; i < size; i++) {
sb.append('0');
}
return sb.toString();
}
..to call it like:
System.out.println(toBinaryString(bitSet.toByteArray(), 64);
run:
0111111101111111011111100000000000000000000000000000000000000000
0111111101111111011111100000000000000000000000000000000000000000
BUILD SUCCESSFUL (total time: 0 seconds)
I m trying to convert 8 bits into one byte. The way the bits are represented are by using a byte object that only contains a 1 or a 0.
If i have a 8 length byte array with these bits, how can i convert them into one byte.
public byte bitsToByte(byte[] bits) {
//Something in here. Each byte inside bits is either a 1 or a 0.
}
Can anyone help?
Thanks
public static byte bitsToByte(byte[] bits){
byte b = 0;
for (int i = 0; i < 8; i++)
b |= (bits[i]&1) << i;
return b;
}
//as an added bonus, the reverse.
public static byte[] bitsToByte(byte bits){
byte[] b = new byte[8];
for (int i = 0; i < 8; i++)
b[i] = (byte) ((bits&(1 << i)) >>> i);
return b;
}
left shift by 1 first for each bit in the array and then add the bit to the byte.
The implementation is based on the assumption that first bit in the array is sign bit and following bits are the magnitude in higher to lower positions of the byte.
public byte bitsToByte(byte[] bits) {
byte value = 0;
for (byte b : bits) {
value <<=1;
value += b;
}
return value;
}
Test the method:
public static void main(String[] args) {
BitsToByte bitsToByte = new BitsToByte();
byte bits[] = new byte[]{0,0,1,0,1,1,0,1}; // 1 + 0 + 4 + 8 + 0 + 32 + 0 + 0
byte value = bitsToByte.bitsToByte(bits);
System.out.println(value);
}
output:
45
Covert the byte array into a byte value (in the same order):
public static byte bitsToByte1(byte[] bits){
byte result = 0;
for (byte i = 0; i < bits.length; i++) {
byte tmp = bits[i];
tmp <<= i; // Perform the left shift by "i" times. "i" position of the bit
result |= tmp; // perform the bit-wise OR
}
return result;
}
input: (same array in reverse)
byte bits1[] = new byte[]{1,0,1,1,0,1,0,0};
value = bitsToByte1(bits1);
System.out.println(value);
output:
45
I have some byte-int operations. But I cant figure out the problem.
First of all I have a hex data and I am holding it as an integer
public static final int hexData = 0xDFC10A;
And I am converting it to byte array with this function:
public static byte[] hexToByteArray(int hexNum)
{
ArrayList<Byte> byteBuffer = new ArrayList<>();
while (true)
{
byteBuffer.add(0, (byte) (hexNum % 256));
hexNum = hexNum / 256;
if (hexNum == 0) break;
}
byte[] data = new byte[byteBuffer.size()];
for (int i=0;i<byteBuffer.size();i++){
data[i] = byteBuffer.get(i).byteValue();
}
return data;
}
And I want to convert 3 byte array to integer back again how can I do that?
Or you can also suggest other converting functions like hex-to-3-bytes-array and 3-bytes-to-int thank you again.
UPDATE
In c# someone use below function but not working in java
public static int byte3ToInt(byte[] byte3){
int res = 0;
for (int i = 0; i < 3; i++)
{
res += res * 0xFF + byte3[i];
if (byte3[i] < 0x7F)
{
break;
}
}
return res;
}
This will give you the value:
(byte3[0] & 0xff) << 16 | (byte3[1] & 0xff) << 8 | (byte3[2] & 0xff)
This assumes, the byte array is 3 bytes long. If you need to convert also shorter arrays you can use a loop.
The conversion in the other direction (int to bytes) can be written with logical operations like this:
byte3[0] = (byte)(hexData >> 16);
byte3[1] = (byte)(hexData >> 8);
byte3[2] = (byte)(hexData);
You could use Java NIO's ByteBuffer:
byte[] bytes = ByteBuffer.allocate(4).putInt(hexNum).array();
And the other way round is possible too. Have a look at this.
As an example:
final byte[] array = new byte[] { 0x00, (byte) 0xdf, (byte) 0xc1, 0x0a };//you need 4 bytes to get an integer (padding with a 0 byte)
final int x = ByteBuffer.wrap(array).getInt();
// x contains the int 0x00dfc10a
If you want to do it similar to the C# code:
public static int byte3ToInt(final byte[] byte3) {
int res = 0;
for (int i = 0; i < 3; i++)
{
res *= 256;
if (byte3[i] < 0)
{
res += 256 + byte3[i]; //signed to unsigned conversion
} else
{
res += byte3[i];
}
}
return res;
}
to convert Integer to hex: integer.toHexString()
to convert hexString to Integer: Integer.parseInt("FF", 16);
public long bin_to_dec() {
int leng = a.length();
for (int i = 0, j = (leng - 1); i < leng; i++, j--) {
int number = Character.getNumericValue(a.charAt(j));
result = result + (number * ((long) Math.pow(2, i)));
}
return result;
}
This code takes a binary string as argument and return it's decimal value .
but for a long string i.e.
(111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111)
it returns -28 .
Why is the memory out of range?
or is my code is incorrect?
You are probably overrunning the length of an int. Integers in java are 32 bit and that binary string is 91 bits.
Try using something like BigInteger instead, which will not overflow. In fact, BigInteger has a built-in method for this:
BigInteger result = new BigInteger(a, 2);