0

I am new to this kind of calculation in java. Here I come up with a task that I will get a Hexadecimal value from CAN , it contains CANId and some value for parameters like wheel speed, engine speed,

If my CANId value is 0xCFF0021 , along with this I get some more data, here If I read the data from starting bit 1.1 up to length 16 bits i will get the Wheel based vehicle speed. How to do that, So for I can understand the reading hexadecimal values but I am not getting values from a particular bit.

import java.util.Scanner;

public class NewClass {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    scan.nextInt(16);
    int[] input = new int[10];
    for (int i = 0; i < 10; i++) {
        //input[i] = scan.nextInt(16);
        //System.out.println(input[i]);
    }
}

}

Roman C
  • 49,761
  • 33
  • 66
  • 176
Raghu
  • 1,324
  • 7
  • 24
  • 47

1 Answers1

0

@Raghu I think this question has been asked here. The simple answer is to convert the hex string to byte as shown in the link I provided. Then you can use bitwise AND operation to mask individual bit positions. For example, to isolate the second bit from the right, you can mask the byte with the number 2. Why?

1111 0110 (value)
0000 0010 (mask)
---------
0000 0010 (isolated bit)

If the value obtain is the same as the mask, the bit position is asserted (high), else it is low. In Java, the bitwise AND and OR operators are '&' and '|' respectively.

Community
  • 1
  • 1
hfontanez
  • 5,774
  • 2
  • 25
  • 37
  • Thank u but what is ment by isolating 2nd or 3rd bit . .? – Raghu Nov 03 '14 at 09:28
  • I m getting exception `Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 7` if I call it as `byte[] b=Example.hexStringToByteArray("0xCFF0021");` – Raghu Nov 03 '14 at 09:36
  • By isolating, I mean the value you get is for that bit or bits alone. Also, try `byte[] b=Example.hexStringToByteArray("CFF0021");` instead. Remember that 'x' is not a hex character. – hfontanez Nov 03 '14 at 12:15