C\#자바 에서 바 이 너 리 숫자 를 읽 을 때의 차이 점

1697 단어 JAVA
올해 나 는 c\#에서 JAVA 로 이동 하여 ANDROID 프로그램 을 썼 는데,JAVA 로 내 가 이전에 C\#로 생 성 한 바 이 너 리 데이터 파일 을 읽 었 을 때 항상 문제 가 있 었 다.그 후에 알 아 낸 것 은 JAVA 와 C\#중 int 와 short 데 이 터 를 저장 할 때 높 은 하위 순서 가 완전히 다 르 기 때 문 입 니 다.따라서 DataInputStream.readShort 또는 DataInputStream.readInt 를 직접 읽 을 수 없습니다.한 바이트 만 읽 고 바이트 순 서 를 거꾸로 해서 short 또는 int 로 맞 출 수 있 습 니 다.
JAVA 코드 는 다음 과 같 습 니 다.
    static int readCsharpInt(InputStream in) throws IOException
    {
        byte[] bytes = new byte[4];
        bytes[3] =(byte)in.read();
        bytes[2] =(byte)in.read();
        bytes[1] =(byte)in.read();
        bytes[0] =(byte)in.read();
        ByteBuffer buffer =  ByteBuffer.wrap(bytes);
        return buffer.getInt();
    }

    static short readCsharpShort(InputStream in) throws IOException
    {
        byte[] bytes = new byte[2];
        bytes[1] =(byte)in.read();
        bytes[0] =(byte)in.read();
        ByteBuffer buffer =  ByteBuffer.wrap(bytes);
        return buffer.getShort();
    }

    static int readJavaInt(InputStream in) throws IOException
    {
        byte[] bytes = new byte[4];
        bytes[0] =(byte)in.read();
        bytes[1] =(byte)in.read();
        bytes[2] =(byte)in.read();
        bytes[3] =(byte)in.read();
        ByteBuffer buffer =  ByteBuffer.wrap(bytes);
        return buffer.getInt();
    }
static short readJavaShort(InputStream in) throws IOException { byte[] bytes = new byte[2]; bytes[0] =(byte)in.read(); bytes[1] =(byte)in.read(); ByteBuffer buffer = ByteBuffer.wrap(bytes); return buffer.getShort(); }
이렇게 하면 정확 하 다.위 에서 읽 은 바이트 의 배열 순서 가 완전히 반대 되 는 것 을 볼 수 있다.

좋은 웹페이지 즐겨찾기