IT/Java
리틀엔디안방식 파일입출력
알라이또
2017. 1. 21. 11:51
반응형
□□□□□□□□□
↑ ↑
A B
리틀엔디안 B에서 부터 읽음.
빅에디안 A에서 부터 읽음
흔히 싼 저가의 보급형 pc들은 리틀엔디안 방식을 사용함. (우리pc)
리틀엔디안방식의 파일에 쓰고, 읽기
import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;public class headTest {public static void main(String[] args) throws IOException {int num = 255;FileOutputStream fos = new FileOutputStream("res/bin.txt");byte[] buf = new byte[4];buf[0] = (byte)num;buf[1] = (byte)(num>>8);buf[2] = (byte)(num>>16);buf[3] = (byte)(num>>24);fos.write(buf); // � 이런식의 우리가 알수없는 바이너리값이 파일에 저장되어있음fos.close();FileInputStream fis = new FileInputStream("res/bin.txt");fis.read(buf);int result = ((int)buf[3]<<24) & 0xff000000 |((int)buf[2]<<16) & 0x00ff0000 |((int)buf[1]<<8) & 0x0000ff00 |((int)buf[0]<<0) & 0x000000ff;// & 0xff00~ 를 하는 이유는 buf[i]를 int로 변환했을때, buf[i]가 음수일때, 앞 비트들이 모두 1로 셋팅되기 때문System.out.println(result); // 결과는 255출력됨}}