seops

[Java] Byte to binary String (Using for BT library) 본문

Android/Android

[Java] Byte to binary String (Using for BT library)

seops 2019. 5. 29. 22:31

Byte to binary String


Sol 1) 

 byte b1 = (byte) 129;

 String s1 = String.format("%8s", Integer.toBinaryString(b1 & 0xFF)).replace(' ', '0');

 System.out.println(s1); // 1000v0001

 

Sol 2) 

 byte b2 = (byte) 2;

 String s2 = String.format("%8S", Integer.toBinaryString(b2 & 0xFF)).replace(' ', '0');

 System.out.println(s2);

 

Ref) https://stackoverflow.com/questions/12310017/how-to-convert-a-byte-to-its-binary-string-representation/12310078

 

How to convert a byte to its binary string representation

For example, the bits in a byte B are 10000010, how can I assign the bits to the string str literally, that is, str = "10000010". Edit I read the byte from a binary file, and stored in the byte ...

stackoverflow.com

Byte ?


(byte) 0x80 -> 1000 0000

(byte) 0x80 -> (int) -128

 

작은 크기의 형이 큰 형으로 변환될 때는 lsb, 즉 부호 비트 값이 왼쪽 모두를 채운다

기대) 1000 0000 -> 0000 0000 0000 0000 0000 0000 1000 0000

실제) 1000 0000 -> 1111 1111 1111 1111 1111 1111 1000 0000

 

즉, 1000 0000의 맨 앞의 1를 부호 비트라고 보고, 큰 변수형으로 커질 떄 왼쪽을 부호 비트로 다 채운다.

따라서, 다음과 같은 작업이 필요하다.

 

int i = (byte & 0xFF) 

1111 1111 1111 1111 1111 1111 1111 1111

0000 0000 0000 0000 0000 0000 1111 1111

-------------------------------------------------------

0000 0000 0000 0000 0000 0000 1111 1111

 

Ref) https://onecellboy.tistory.com/345

 

[JAVA] byte to int, double, etc (혹은 그반대) 등 코드포함

자바에서 바이트배열을 수로 바꾸기, 수를 바이트배열로 바꾸기 참고사항 byte 에서 int 로 형변환시 lsb 가 커진다. 무슨 말이냐 하면 byte 가 0x80라 하자. 그럼 1000 0000 이다. byte 를 부호있는 십진수로 보..

onecellboy.tistory.com

Usage


2byte -> (binary) 0000 0000 0000 0000b

 

1차 가공 : (byte value) & (0xFF)

 

확인 절차 - MASK 값 이용

0x10 - 0001 0000

0x20 - 0010 0000

0x40 - 0100 0000

0x80 - 1000 0000

0xF0 - 1111 0000

 

tempShort[0] = packetData[index++];

byte pr_data = (tempShort[0] & 0xFF);  // 1차 가공 처리

 

// Check each bit in first 4bit

0x1F

0x2F

0x4F

0x8F

위 byte와 각각을 & 해줄 경우, 동일하게 나오면 해당 부분에 값이 있음을 알 수 있다.

 

// Check whole bit in 1 byte

0xFF와 & 연산을 할 경우, 동일하게 나오면 해당 부분에 값이 있음을 알 수 있다.

'Android > Android' 카테고리의 다른 글

[Firebase] 3. SimplePush  (0) 2020.10.04
[Firebase] 2. Push Notification 로직 구상  (0) 2020.09.22
[Firebase] 1. Push Notification 연동  (0) 2020.09.21
[200301] [Works] [App] Grid-Layout  (0) 2020.03.01
Bluetooth 정리  (0) 2020.01.14
Comments