Java 바이트 기본 유형에 대한 실제 용도가 있습니까?
설명 할 수없는 이유 때문에 byte기본 유형은 Java로 서명됩니다. 즉, 유효한 값은 바이트에서 8 개의 중요한 비트 (부호 비트 없음)를 나타내는 일반적인 0..255 범위 대신 -128..127입니다.
이것은 모든 바이트 조작 코드가 일반적으로 정수 계산을 수행하고 마지막 8 비트를 마스킹한다는 것을 의미합니다.
이 있는지 궁금 해서요 어떤 자바 실제 시나리오 byte원시적 형태가 완벽하거나 단순히 완전히 쓸모 디자인 결정의 경우에 맞는가?
편집 : 유일한 실제 사용 사례는 네이티브 코드에 대한 단일 바이트 자리 표시 자였습니다. 즉, Java 코드 내에서 바이트로 조작되지 않습니다.
편집 : 이제 내부 꽉 루프가 7 (숫자 0..32)로 나눌 필요가있는 곳을 보았습니다. 따라서 조회 테이블은 데이터 유형으로 바이트로 수행 될 수 있으므로 L1 캐시 사용량을 생각하면 메모리 사용량이 낮게 유지 될 수 있습니다. . 이것은 서명 된 / 서명되지 않은 것을 의미하는 것이 아니라 실제 사용의 경우입니다.
놀랍게도 저는 byte지난주 처음으로 Java를 사용 했기 때문에 (비정상적이긴하지만) 사용 사례가 있습니다. Java 에서 호출 할 수있는 라이브러리에서 함수를 구현할 수 있는 네이티브 Java 함수를 작성했습니다 . Java 유형은 기본 언어 (이 경우 C)의 유형으로 변환되어야합니다.
이 함수는 바이트 배열을 가져와야했지만 ( byte당시 유형을 완전히 잊어 버림 ) char[]. 자바는 C 함수에 대해 생성 서명은 해당 파라미터의 타입 부여 jcharArray하는 무리로 변환 될 수 있고, jchar에 혼성 타입 정의되는 S, jni.h행을 unsigned short. 당연히 같은 크기는 아닙니다. 1이 아닌 2 바이트입니다. 이로 인해 기본 코드에 모든 종류의 문제가 발생했습니다. 자바 유형을 만들기 byte[]A의 결과 jbyteArray, 그리고 jbyte리눅스은에 형식 정의 - 에드입니다 signed char적당한 크기이다,
Josh Bloch는 최근 프레젠테이션 에서 이것이 언어의 실수 중 하나라고 언급했습니다 .
그 이유는 java에 부호없는 숫자 유형이 없으며 byte해당 규칙을 준수해야하기 때문이라고 생각합니다 . (참고 : char은 부호가 없지만 숫자를 나타내지 않음)
특정 질문에 관해서는 : 나는 어떤 예도 생각할 수 없습니다. 그리고 예제가 있더라도 0..255보다 적을 것이고 마스킹을 사용하여 구현할 수 있습니다 (대부분이 아닌).
byte, short, char 공간을 절약하기 위해 배열에서 사용되는 경우를 제외하고 유형은 대부분 쓸모가 없습니다.
나도 자바 또는 JVM은 그들을 위해 실제 지원이 없습니다. 그들에 대한 거의 모든 작업은 그들을 먼저 int또는 long먼저 승격시킬 것 입니다. 우리는 같은 것을 쓸 수도 없습니다
short a=1, b=2;
a = a + b; // illegal
a = a << 1; // illegal
그렇다면 왜 byte, short, char유형에 대한 작업을 정의하는 데 신경 쓰는 이유는 무엇입니까?
그들이하는 일은 프로그래머를 놀라게 할 변환을 확대하는 것입니다.
8 비트 부호있는 샘플을 사용하는 디지털화 된 사운드 (또는 다른 신호)는 나에게 유일한 합리적인 예처럼 보입니다. 물론 서명 된 바이트를 갖는 것은 그러한 신호를 처리하는 데 필요하지 않으며 Java 바이트가 "완벽하게 맞는지"논쟁 할 수 있습니다.
개인적으로 서명하지 않은 것은 실수라고 생각합니다. unsigned bytes / ints에 대한 사용이 더 많기 때문일뿐만 아니라 더 강력한 유형 시스템을 선호하기 때문입니다. 음수가 유효하지 않음을 지정하고 컴파일러 검사 및 위반에 대한 런타임 예외를 허용하면 좋을 것입니다.
byteJava Card 용 애플릿 개발에 광범위하게 사용됩니다. 카드에는 제한된 리소스가 있기 때문에 모든 메모리는 소중합니다. 그런데 카드 프로세서는 정수 값 처리에 제한이 있습니다. int유형 지원은 선택 사항이며 java.lang.String지원되지 않으므로 모든 정수 연산 및 데이터 저장은 byte및 short변수 및 배열에서 수행됩니다 . 정수 리터럴은 int유형이므로 전체 코드 로 byte또는 short전체 코드 로 명시 적으로 캐스트되어야합니다 . 카드와의 통신은 명령 클래스, 명령 및 매개 변수를 디코딩 byte하기 위해 bytes로 분해되어야 하는 배열로 애플릿에 전달되는 APDU 명령을 통해 진행됩니다 . 다음 코드를 보면 Java 카드 개발에 얼마나 많은 유형 byte과 short유형이 중요한지 알 수 있습니다.
package somepackage.SomeApplet;
import javacard.framework.*;
import org.globalplatform.GPSystem;
import org.globalplatform.SecureChannel;
public class SomeApplet extends Applet {
// Card status
private final static byte ST_UNINITIALIZED = (byte) 0x01;
private final static byte ST_INITIALIZED = (byte) 0x02;
// Instructions & Classes
private final static byte PROP_CLASS = (byte) 0x80;
private final static byte INS_INIT_UPDATE = (byte) 0x50;
private final static byte INS_EXT_AUTH = (byte) 0x82;
private final static byte INS_PUT_DATA = (byte) 0xDA;
private final static byte INS_GET_RESPONSE = (byte) 0xC0;
private final static byte INS_GET_DATA = (byte) 0xCA;
private final static short SW_CARD_NOT_INITIALIZED = (short) 0x9101;
private final static short SW_CARD_ALREADY_INITIALIZED = (short) 0x9102;
private final static byte OFFSET_SENT = 0x00;
private final static byte OFFSET_RECV = 0x01;
private static short[] offset;
private static byte[] fileBuffer;
private static short fileSize = 0;
public static void install(byte[] bArray, short bOffset, byte bLength) {
new SomeApplet( bArray, bOffset, bLength);
}
public RECSApplet(byte[] bArray, short bOffset, byte bLength) {
offset = JCSystem.makeTransientShortArray((short) 2, JCSystem.CLEAR_ON_RESET);
fileBuffer = new byte[FILE_SIZE];
byte aidLen = bArray[bOffset];
if (aidLen== (byte)0){
register();
} else {
register(bArray, (short)(bOffset+1), aidLen);
}
}
public void process(APDU apdu) {
if (selectingApplet()) {
return;
}
byte[] buffer = apdu.getBuffer();
short len = apdu.setIncomingAndReceive();
byte cla = buffer[ISO7816.OFFSET_CLA];
byte ins = buffer[ISO7816.OFFSET_INS];
short lc = (short) (buffer[ISO7816.OFFSET_LC] & 0x00ff);
while (len < lc) {
len += apdu.receiveBytes(len);
}
SecureChannel sc = GPSystem.getSecureChannel();
if ((short)(cla & (short)0x80) == ISO7816.CLA_ISO7816) {
switch (ins) {
case INS_PUT_DATA:
putData(buffer, ISO7816.OFFSET_CDATA, offset[OFFSET_RECV], len);
if ((cla & 0x10) != 0x00) {
offset[OFFSET_RECV] += len;
} else {
fileSize = (short) (offset[OFFSET_RECV] + len);
offset[OFFSET_RECV] = 0;
}
return;
case INS_GET_DATA:
case INS_GET_RESPONSE:
sendData(apdu);
return;
default:
ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
}
}
else if ((byte) (cla & PROP_CLASS) == PROP_CLASS) {
switch (ins) {
case INS_INIT_UPDATE:
case INS_EXT_AUTH:
apdu.setOutgoingAndSend(ISO7816.OFFSET_CDATA, sc.processSecurity(apdu));
return;
default:
ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
}
} else
ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED);
}
// Some code omitted
}
I think it is signed in order to be consistent with short and int.
As to whether it is used much, it makes the notion of "byte arrays" a construct rather than a primitive.
That's really all I have. :)
On a machine with words larger than 8 bits it's somewhat useful if you wish to store a lot of values that fit in an 8-bit range into a single array, but typically it's not a good idea to use them otherwise since a byte is actually more effort to get out of memory than an int.
Remember though that Java was designed for very small consumer devices (set-top TV boxes). I expect if it had been used this way on small 8-bit microprocessors it would have been more useful as it would fit the word size exactly and could be used for general "Math" operations on a very small scale.
The only reason I can see to make it signed is that an unsigned byte interacting with an int can be a little confusing--but I'm not convinced it's any more confusing than a signed one is!
The size of byte is 8 bits. The size of byte helps in processing input and output while performing functions like writing to a file or reading from a file. Consider a scenario in which you want to read an input from the keyboard or from any file. If you use the "byte" data structure, you know that you are receiving one character at a time since the size is 8 bits. So every time you receive an input stream, you know that you are actually receiving one character at a time.
I used it frequently when I was programming software and games for J2ME. On most J2ME-devices, you have limited resources, so storing for example the map of a level in a byte-array is less resource-intensive than storing it in an int-array.
I am using bytes right now in java for a bluetooth android project.
ReferenceURL : https://stackoverflow.com/questions/6892444/are-there-any-real-life-uses-for-the-java-byte-primitive-type
'Program Club' 카테고리의 다른 글
| Unix에서 경로의 일부 제거 (0) | 2021.01.05 |
|---|---|
| 난독 화 된 코드에서 문자열 숨기기 (0) | 2020.12.31 |
| * args, ** jinja2 매크로의 kwargs (0) | 2020.12.31 |
| C #으로 플로팅 (0) | 2020.12.31 |
| Commodore 64에서 화면 테두리에 그리기 (0) | 2020.12.31 |