在java中如何将十六进制字符串分离为单独的位值?

kzipqqlq  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(440)

使用以下命令成功将字节数组转换为十六进制字符串后:

  1. private ScanCallback leScanCallback = new ScanCallback() {
  2. @Override
  3. public void onScanResult(int callbackType, ScanResult result) {
  4. ScanRecord Scanned = result.getScanRecord();
  5. String address = btAdapter.getAddress();
  6. byte[] packetData = Scanned.getBytes();
  7. StringBuilder R = new StringBuilder();
  8. for(byte hex : packetData){
  9. R.append(String.format("%02X", hex));
  10. }

我想现在有能力读取十六进制流的每一位分别作为数值,以允许对我的ble扫描仪应用程序的值执行基本逻辑。
我读过很多网站,我最初的想法是在for循环中使用数组并读入十六进制字符串的每个字符。但我是java新手,还没有成功做到这一点!
任何关于我如何能有效地做到这一点的想法都会很好。
编辑:
初始输出使用getbytes()并给出一个字节数组输出,如“[b@”,后跟一些数字和字母。这个值不是我需要的格式,我需要62位十六进制流,由于for循环,它现在已经成功打印了!
现在我想将62位数据包长度的十六进制数据分离为单独的当前值。不将它们转换回字节数组。
希望这能进一步澄清这些要求
编辑:到目前为止完整的代码

  1. package com.example.joelwasserman.androidbletutorial;
  2. import android.Manifest;
  3. import android.app.AlertDialog;
  4. import android.bluetooth.BluetoothAdapter;
  5. import android.bluetooth.BluetoothDevice;
  6. import android.bluetooth.BluetoothManager;
  7. import android.bluetooth.le.BluetoothLeScanner;
  8. import android.bluetooth.le.ScanCallback;
  9. import android.bluetooth.le.ScanFilter;
  10. import android.bluetooth.le.ScanRecord;
  11. import android.bluetooth.le.ScanResult;
  12. import android.content.Context;
  13. import android.content.DialogInterface;
  14. import android.content.Intent;
  15. import android.content.pm.PackageManager;
  16. import android.location.Location;
  17. import android.location.LocationManager;
  18. import android.os.AsyncTask;
  19. import android.os.ParcelUuid;
  20. import android.support.v4.app.ActivityCompat;
  21. import android.support.v4.content.ContextCompat;
  22. import android.support.v7.app.AppCompatActivity;
  23. import android.os.Bundle;
  24. import android.text.method.ScrollingMovementMethod;
  25. import android.util.Log;
  26. import android.util.SparseArray;
  27. import android.view.View;
  28. import android.widget.Button;
  29. import android.widget.TextView;
  30. import java.io.IOException;
  31. import java.io.StringReader;
  32. import java.nio.charset.StandardCharsets;
  33. import java.util.List;
  34. import java.util.UUID;
  35. import java.util.Vector;
  36. public class MainActivity extends AppCompatActivity {
  37. BluetoothManager btManager;
  38. BluetoothAdapter btAdapter;
  39. BluetoothLeScanner btScanner;
  40. Button startScanningButton;
  41. Button stopScanningButton;
  42. TextView peripheralTextView;
  43. private final static int REQUEST_ENABLE_BT = 1;
  44. private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
  45. @Override
  46. protected void onCreate(Bundle savedInstanceState) {
  47. super.onCreate(savedInstanceState);
  48. setContentView(R.layout.activity_main);
  49. peripheralTextView = (TextView) findViewById(R.id.PeripheralTextView);
  50. peripheralTextView.setMovementMethod(new ScrollingMovementMethod());
  51. startScanningButton = (Button) findViewById(R.id.StartScanButton);
  52. startScanningButton.setOnClickListener(new View.OnClickListener() {
  53. public void onClick(View v) {
  54. startScanning();
  55. }
  56. });
  57. stopScanningButton = (Button) findViewById(R.id.StopScanButton);
  58. stopScanningButton.setOnClickListener(new View.OnClickListener() {
  59. public void onClick(View v) {
  60. stopScanning();
  61. }
  62. });
  63. stopScanningButton.setVisibility(View.INVISIBLE);
  64. btManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
  65. btAdapter = btManager.getAdapter();
  66. btScanner = btAdapter.getBluetoothLeScanner();
  67. if (btAdapter != null && !btAdapter.isEnabled()) {
  68. Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  69. startActivityForResult(enableIntent,REQUEST_ENABLE_BT);
  70. }
  71. // Make sure we have access coarse location enabled, if not, prompt the user to enable it
  72. if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  73. final AlertDialog.Builder builder = new AlertDialog.Builder(this);
  74. builder.setTitle("This app needs location access");
  75. builder.setMessage("Please grant location access so this app can detect peripherals.");
  76. builder.setPositiveButton(android.R.string.ok, null);
  77. builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
  78. @Override
  79. public void onDismiss(DialogInterface dialog) {
  80. requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
  81. }
  82. });
  83. builder.show();
  84. }
  85. }
  86. // Device scan callback.
  87. private ScanCallback leScanCallback = new ScanCallback() {
  88. @Override
  89. public void onScanResult(int callbackType, ScanResult result) {
  90. ScanRecord Scanned = result.getScanRecord();
  91. String address = btAdapter.getAddress();
  92. byte[] packetData = Scanned.getBytes();
  93. /*StringBuilder R = new StringBuilder();
  94. for(byte hex : packetData){
  95. R.append(String.format("%02X", hex));
  96. }*/
  97. int PacketLength = Scanned.getBytes().length;
  98. // int x = Integer.parseInt(String.valueOf(packetData));
  99. // String int_val = Integer.toString(x);
  100. if(new String("SimpleBLEBroadcaster").equals(result.getDevice().getName()))
  101. peripheralTextView.append("Device Name: " + result.getDevice().getName() + " rssi: " + result.getRssi() +" Packet length: " + PacketLength + " Packet Data: " + "0x" + R + "\n");
  102. }
  103. };
  104. @Override
  105. public void onRequestPermissionsResult(int requestCode,
  106. String permissions[], int[] grantResults) {
  107. switch (requestCode) {
  108. case PERMISSION_REQUEST_COARSE_LOCATION: {
  109. if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  110. System.out.println("coarse location permission granted");
  111. } else {
  112. final AlertDialog.Builder builder = new AlertDialog.Builder(this);
  113. builder.setTitle("Functionality limited");
  114. builder.setMessage("Since location access has not been granted, this app will not be able to discover beacons when in the background.");
  115. builder.setPositiveButton(android.R.string.ok, null);
  116. builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
  117. @Override
  118. public void onDismiss(DialogInterface dialog) {
  119. }
  120. });
  121. builder.show();
  122. }
  123. return;
  124. }
  125. }
  126. }
  127. public void startScanning() {
  128. System.out.println("start scanning");
  129. peripheralTextView.setText("");
  130. startScanningButton.setVisibility(View.INVISIBLE);
  131. stopScanningButton.setVisibility(View.VISIBLE);
  132. AsyncTask.execute(new Runnable() {
  133. @Override
  134. public void run() {
  135. btScanner.startScan(leScanCallback);
  136. }
  137. });
  138. }
  139. public void stopScanning() {
  140. System.out.println("stopping scanning");
  141. peripheralTextView.append("Stopped Scanning");
  142. startScanningButton.setVisibility(View.VISIBLE);
  143. stopScanningButton.setVisibility(View.INVISIBLE);
  144. AsyncTask.execute(new Runnable() {
  145. @Override
  146. public void run() {
  147. btScanner.stopScan(leScanCallback);
  148. }
  149. });
  150. }
  151. public static byte[] hexStringToByteArray(String s) throws IOException {
  152. char[] buf = new char[2];
  153. int numRead = -1;
  154. StringReader in = new StringReader(s);
  155. byte[] bytes = new byte[s.length() / 2];
  156. int byteIndex = 0;
  157. while ((numRead = in.read(buf)) > -1) {
  158. byte b = (byte) Integer.parseInt(String.valueOf(buf), 16);
  159. bytes[byteIndex++] = b;
  160. }
  161. return bytes;
  162. }
  163. }
roejwanj

roejwanj1#

记住我所说的交通与可视化,你所得到的可以通过以下方式处理:

  1. public static byte[] hexStringToByteArray(String s) throws IOException {
  2. char[] buf = new char[2];
  3. int numRead = -1;
  4. StringReader in = new StringReader(s);
  5. byte[] bytes = new byte[s.length() / 2];
  6. int byteIndex = 0;
  7. while ((numRead = in.read(buf)) > -1) {
  8. byte b = (byte) Integer.parseInt(String.valueOf(buf), 16);
  9. bytes[byteIndex++] = b;
  10. }
  11. return bytes;
  12. }

相关问题