2016-09-28 4 views
0

소켓 응용 프로그램이 있고 바이트 단위로 읽을 수 있으며 모든 바이트를 하나의 단일 배열로 푸시 할 수 있습니다. 나는 아래처럼 읽는다. 나는 12 + bodylen 바이트를 가질 것이다.바이트 단위로 바이트를 xor해야하지만 정수로 표시되고 정밀도 오류가 손실됩니까?

int messageID = r.readUnsignedShort(); 
int bodyLen = r.readUnsignedShort();  
byte[] phoneNum = new byte[6]; 
r.readFully(phoneNum); 
int serialNum = r.readUnsignedShort();  
byte[] messageBody = new byte[bodyLen];  
r.readFully(messageBody); 
byte checkCode = r.readByte(); 

다음 값 중 하나가 -110 원인 나는 ByteBuffer를을 만들 경우이 작업을 수행하고 나중에 나는 그것의 바이트 형식 여부를 내가 정수 값에받을 경우 확인하기 위해 먼저 인쇄 for 루프를 실행하려고 ? 또한이 줄에 오류가 발생합니다. xor = (byte) xor^(byte) fullMessage [sf]; 정밀도의 손실 가능성? 먼저

ByteBuffer buf = ByteBuffer.allocate(12+bodyLen); 
      buf.putShort((short)messageID); 
      buf.put((byte)bodyLen); 
      buf.put(phoneNum); 
      buf.putShort((short)serialNum); 
      buf.put(messageBody); 

      byte[] fullMessage=buf.array(); 

      int xor = 0; 
      for(int sf=0,s=fullMessage.length;sf<s;sf++){ 
       xor ^= fullMessage[sf]; 
       fullMessage[sf] = (byte)xor; 
      // System.out.println("\n\nprint value for : "+sf+" "+"value is:"+xor); 
       // do your XOR operations -> xor operator is^
      } 
      System.out.println("\n\nfinal xor is :"+xor+" "+Integer.toHexString(xor)); 

답변

1

당신이하고 있기 때문에 :

int serialNum = r.readUnsignedShort();  

buf.putShort((short)serialNum); 
,369에 의해

buf.put((byte)serialNum); 

교체

기호가 값을 비뚤어 지지만 그 값은 & 0xFFFF으로 복구 할 수 있습니다.

byte x = (byte) 0xA0; // Negative signed byte value 
byte y = ... 
byte z = (byte)(x^y); // Xor is done on int 

는 그래서 xorring 될 것이다 :

바이트로되어 xorred

int xor = 0; 
    for (int sf = 0, s = fullMessage.length; sf < s; sf++) { 
     xor ^= fullMessage[sf]; 
     fullMessage[sf] = (byte)xor; 
    } 

가 0 ^의 중성 원소 인 것을 사용.

+0

ok이 buf.put (byte) bodyLen); – user5313398

+0

동일한 원칙. 물론 메시지 바이트를 줄이는 것이 의도적이지 않을 때, 일부를 남겨 두었습니다. –

+0

나는 내 질문을 업데이 트했지만 xor에 대한 잘못된 값을 얻는다. – user5313398

1

xor = (byte) ((byte)xor^(byte)fullMessage[sf]);