Advertisement
Guest User

Untitled

a guest
Jan 26th, 2015
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.05 KB | None | 0 0
  1. import java.io.IOException;
  2. import java.nio.ByteBuffer;
  3.  
  4. public class ErlPorts {
  5.  
  6.     private static int readLine(byte[] bytes) {
  7.         try {
  8.             int len;
  9.             if (readExact(bytes, 2) != 2)
  10.                 return -1;
  11.             len = (bytes[0] << 8) | bytes[1];
  12.             return readExact(bytes, len);
  13.         } catch (IOException e) {
  14.             e.printStackTrace();
  15.         }
  16.         return -1;
  17.     }
  18.  
  19.     private static int writeLine(byte[] bytes, int length) {
  20.         byte[] li;
  21.         li = ByteBuffer.allocate(4).putInt((length >> 8) & 0xff).array();
  22.         writeExact(li, 1);
  23.         li = ByteBuffer.allocate(4).putInt(length & 0xff).array();
  24.         writeExact(li, 1);
  25.         return writeExact(bytes, length);
  26.     }
  27.  
  28.     private static int readExact(byte[] bytes, int length) throws IOException{
  29.         int in_count = length;
  30.         int offset = 0;
  31.         do
  32.         {
  33.             int c = System.in.read (bytes, offset, in_count-offset);
  34.             offset += c;
  35.         }
  36.         while (offset < in_count);
  37.         return(in_count);
  38.     }
  39.  
  40.     //ta funkcja to jakieś gówno i nie ma prawa działać
  41.     private static int writeExact(byte[] bytes, int length) {
  42.         int out_count = length;
  43.         int offset = 0;
  44.         do
  45.         {
  46.             System.out.write (bytes, 0, out_count);
  47.             offset += 2;
  48.         }
  49.         while (offset < out_count);
  50.         return(out_count);
  51.     }
  52.  
  53.     private static int foo(int arg) {
  54.         return arg*2;
  55.     }
  56.  
  57.     private static int bar(int arg) {
  58.         return arg/2;
  59.     }
  60.  
  61.     public static void main(String[] args) {
  62.         int fn, arg, res = -1;
  63.         byte[] buf = new byte[100];
  64.  
  65.         while (readLine(buf) > 0) {
  66.             fn = buf[0];
  67.             arg = buf[1];
  68.  
  69.             if (fn == 1) {
  70.                 res = foo(arg);
  71.             } else if (fn == 2) {
  72.                 res = bar(arg);
  73.             }
  74.             buf[0] = ByteBuffer.allocate(4).putInt(res).array()[0];
  75.             writeLine(buf, 1);
  76.         }
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement