바이트를 이진 암호화 표현으로 변환하는 방법
예를 들어, 바이트의 비트가 B
있다 10000010
, 나는 호스트로 비트를 할당하는 방법을 str
, 문자 그대로를 str = "10000010"
.
편집하다
바이너리 파일에서 바이트를 읽고 바이트 배열에 저장했습니다 B
. 나는 System.out.println(Integer.toBinaryString(B[i]))
. 문제는
(a) 비트가 (가장 왼쪽) 1로 시작 B[i]
하면 음의 int 값으로 변환이 출력이 .
비트와 함께 시작하는 경우 (b) 0
의 출력이 무시 0
, 예를 들어, 가정, B[0]
00000001 있고, 출력은 1
대신00000001
byte b1 = (byte) 129;
String s1 = String.format("%8s", Integer.toBinaryString(b1 & 0xFF)).replace(' ', '0');
System.out.println(s1); // 10000001
byte b2 = (byte) 2;
String s2 = String.format("%8s", Integer.toBinaryString(b2 & 0xFF)).replace(' ', '0');
System.out.println(s2); // 00000010
스탬핑 .
나는 이것을 사용했다. 다른 답변과 검색 아이디어이지만 어디서나 정확한 접근 방식을 발견합니다. :)
System.out.println(Integer.toBinaryString((b & 0xFF) + 0x100).substring(1));
0xFF
255 또는 11111111
(부호없는 바이트의 최대 값)입니다. 0x100
256 또는100000000
는 &
정수로 바이트 업 캐스팅. 이 시점에서 0
- 255
( 00000000
~ 11111111
, 나는 선행 24 비트를 제외했습니다). + 0x100
및 .substring(1)
선행 0이 될 것입니다.
나는 João Silva의 답변 과 비교하여 시간을 측정 합니다. http://ideone.com/22DDK1 Pshemo의 대답은 제대로 패딩되지 않았는지 여부.
이것이 당신이 찾고있는 것입니까?
바이트에서 바이트로 변환
byte b = (byte)(int)Integer.valueOf("10000010", 2);
System.out.println(b);// output -> -126
바이트에서 공유로 변환
System.out.println(Integer.toBinaryString((b+256)%256));// output -> "10000010"
주앙 실바가 또는 자신의 의견에 말했듯이 선두 추가 0
같은 문자열의 경우, 우리는 길이 8 문자열을 포맷하고 0 결과 선행 공백으로을 대체 할 수있는 " 1010"
우리가 얻을 것이다"00001010"
System.out.println(String.format("%8s", Integer.toBinaryString((b + 256) % 256))
.replace(' ', '0'));
바이트의 각 비트를 확인한 다음 0 또는 1을 추가 할 수 있습니다. 다음은 테스트를 위해 회의 작은 도우미 방법입니다.
public static String byteToString(byte b) {
byte[] masks = { -128, 64, 32, 16, 8, 4, 2, 1 };
StringBuilder builder = new StringBuilder();
for (byte m : masks) {
if ((b & m) == m) {
builder.append('1');
} else {
builder.append('0');
}
}
return builder.toString();
}
이 코드는 java int가 4 개의 연속 바이트로 분할되는 방법을 보여줍니다. 그런 다음 낮은 수준의 바이트 / 비트 질문과 비교하여 Java 메소드를 사용하여 각 바이트를 검사 할 수 있습니다.
아래 코드를 사용할 때 예상되는 출력입니다.
[Input] Integer value: 8549658
Integer.toBinaryString: 100000100111010100011010
Integer.toHexString: 82751a
Integer.bitCount: 10
Byte 4th Hex Str: 0
Byte 3rd Hex Str: 820000
Byte 2nd Hex Str: 7500
Byte 1st Hex Str: 1a
(1st + 2nd + 3rd + 4th (int(s)) as Integer.toHexString: 82751a
(1st + 2nd + 3rd + 4th (int(s)) == Integer.toHexString): true
Individual bits for each byte in a 4 byte int:
00000000 10000010 01110101 00011010
음성 코드는 다음과 달라집니다.
public class BitsSetCount
{
public static void main(String[] args)
{
int send = 8549658;
System.out.println( "[Input] Integer value: " + send + "\n" );
BitsSetCount.countBits( send );
}
private static void countBits(int i)
{
System.out.println( "Integer.toBinaryString: " + Integer.toBinaryString(i) );
System.out.println( "Integer.toHexString: " + Integer.toHexString(i) );
System.out.println( "Integer.bitCount: "+ Integer.bitCount(i) );
int d = i & 0xff000000;
int c = i & 0xff0000;
int b = i & 0xff00;
int a = i & 0xff;
System.out.println( "\nByte 4th Hex Str: " + Integer.toHexString(d) );
System.out.println( "Byte 3rd Hex Str: " + Integer.toHexString(c) );
System.out.println( "Byte 2nd Hex Str: " + Integer.toHexString(b) );
System.out.println( "Byte 1st Hex Str: " + Integer.toHexString(a) );
int all = a+b+c+d;
System.out.println( "\n(1st + 2nd + 3rd + 4th (int(s)) as Integer.toHexString: " + Integer.toHexString(all) );
System.out.println("(1st + 2nd + 3rd + 4th (int(s)) == Integer.toHexString): " +
Integer.toHexString(all).equals(Integer.toHexString(i) ) );
System.out.println( "\nIndividual bits for each byte in a 4 byte int:");
/*
* Because we are sending the MSF bytes to a method
* which will work on a single byte and print some
* bits we are generalising the MSF bytes
* by making them all the same in terms of their position
* purely for the purpose of printing or analysis
*/
System.out.print(
getBits( (byte) (d >> 24) ) + " " +
getBits( (byte) (c >> 16) ) + " " +
getBits( (byte) (b >> 8) ) + " " +
getBits( (byte) (a >> 0) )
);
}
private static String getBits( byte inByte )
{
// Go through each bit with a mask
StringBuilder builder = new StringBuilder();
for ( int j = 0; j < 8; j++ )
{
// Shift each bit by 1 starting at zero shift
byte tmp = (byte) ( inByte >> j );
// Check byte with mask 00000001 for LSB
int expect1 = tmp & 0x01;
builder.append(expect1);
}
return ( builder.reverse().toString() );
}
}
각 바이트의 비트를 가져 와서 문자열로 변환합니다. 바이트에 8 비트가 있다고 가정하면 비트 이동을 통해 하나씩 얻을 수 있습니다. 예를 들어, 바이트의 두 번째 비트를 6 비트 오른쪽으로, 두 번째 비트를 8 비트의 마지막 비트로 이동 한 다음, and (&)를 0x0001로 이동하여 앞쪽 비트를 정리합니다.
public static String getByteBinaryString(byte b) {
StringBuilder sb = new StringBuilder();
for (int i = 7; i >= 0; --i) {
sb.append(b >>> i & 1);
}
return sb.toString();
}
조금 늦었다는 것을 알고 죄송합니다 ...하지만 훨씬 쉬운 방법이 있습니다 ... 이진 문자열로 :
//Add 128 to get a value from 0 - 255
String bs = Integer.toBinaryString(data[i]+128);
bs = getCorrectBits(bs, 8);
getCorrectBits 메서드 :
private static String getCorrectBits(String bitStr, int max){
//Create a temp str to add all the zeros
String tmpStr = "";
for(int i = 0; i < (max - bitStr.length()); i ++){
tmpStr += "0";
}
return tmpStr + bitStr;
}
Integer.toBinaryString((byteValue & 0xFF) + 256).substring(1)
String byteToBinaryString(byte b){
StringBuilder binaryStringBuilder = new StringBuilder();
for(int i = 0; i < 8; i++)
binaryStringBuilder.append(((0x80 >>> i) & b) == 0? '0':'1');
return binaryStringBuilder.toString();
}
우리 모두는 Java가 unsigned 키워드와 같은 것을 제공하지 않는다는 것을 알고 있습니다. 또한 byte
Java의 사양에 따른 기본 형식은 −128
과 사이의 값을 나타냅니다 127
. 예를 들어,이 경우 byte
입니다 cast
에 int
자바 첫 번째 해석합니다 bit
는 AS sign
및 사용 부호 확장.
그런 다음보다 큰 바이트 127
를 이진 문자열 표현 으로 변환하는 방법 ??
아무것도 시청에서 당신을 방해하지 않습니다 byte
사이의 값으로 그 비트를 단순히 8 비트를 해석 0
하고 255
. 또한 다른 사람의 방법에 대한 해석을 강요하기 위해 할 수있는 일이 없다는 것을 명심해야합니다. 방법이를 수락하면 byte
, 그 방법은 사이의 값을 허용 −128
하고 127
명시 적으로 달리 명시되지 않는.
따라서이를 해결하는 가장 좋은 방법 은 메서드 를 호출 하거나 기본 형식 으로 캐스팅 하여 byte
값을 값으로 변환하는 것 입니다. 여기에 예가 있습니다.int
Byte.toUnsignedInt()
int
(int) signedByte & 0xFF
public class BinaryOperations
{
public static void main(String[] args)
{
byte forbiddenZeroBit = (byte) 0x80;
buffer[0] = (byte) (forbiddenZeroBit & 0xFF);
buffer[1] = (byte) ((forbiddenZeroBit | (49 << 1)) & 0xFF);
buffer[2] = (byte) 96;
buffer[3] = (byte) 234;
System.out.println("8-bit header:");
printBynary(buffer);
}
public static void printBuffer(byte[] buffer)
{
for (byte num : buffer) {
printBynary(num);
}
}
public static void printBynary(byte num)
{
int aux = Byte.toUnsignedInt(num);
// int aux = (int) num & 0xFF;
String binary = String.format("%8s', Integer.toBinaryString(aux)).replace(' ', '0');
System.out.println(binary);
}
}
산출
8-bit header:
10000000
11100010
01100000
11101010
여기서 추측하지만 Byte가있는 경우 객체에서 toString ()을 호출하여 값을 가져올 수 없습니까? 또는 byteValue ()를 사용하여 api를 살펴 보 시겠습니까?
'ProgramingTip' 카테고리의 다른 글
React로 현재 전체 URL을 개발시겠습니까? (0) | 2020.10.11 |
---|---|
저장소와 서비스의 차이점은 무엇입니까? (0) | 2020.10.11 |
null 값에 대한 jdk8 스트림을 관리하는 방법 (0) | 2020.10.11 |
속성 파일에서 등호 기호를 이스케이프하는 방법 (0) | 2020.10.11 |
두 숫자 사이에 UILabel 텍스트를 애니메이션 확장? (0) | 2020.10.11 |