2 Replies Latest reply: Jun 13, 2008 6:23 AM by 807591 RSS

    C to Java bit shifting/masks

    807591
      Hello,

      I apologise if this is posted in the wrong forums and would appreciate it if someone could point me in the right direction if this is the case.

      I have some C code which I would like to translate into Java and am having a problem with the following piece of code:

      In C:
      static int encodeUInt32(unsigned int n, unsigned char* buf, int bufsz)
      {
          if (bufsz < 4) return -1;
      
      
          *buf++ = (n >> 24) & 0xFF;
          *buf++ = (n >> 16) & 0xFF;
          *buf++ = (n >>  8) & 0xFF;
          *buf++ = (n >>  0) & 0xFF;
      
          return 4;
      }
      I have modified this accordingly in Java to:
          private int encodeUInt32(long n, char[] buf, int bufsz){
              if (bufsz < 4)
                  return -1;
              
              int count = 0;
              
              buf[count++] = (char)((n >> 24) & 0xFF);
              buf[count++] = (char)((n >> 16) & 0xFF);
              buf[count++] = (char)((n >>  8) & 0xFF);
              buf[count++] = (char)((n >>  0) & 0xFF);
              
              return 4;
          }
      Everything seems sound except the bit-shifting/masking. For instance, if I run:
      encodeUInt32(40966, &char[32], 32)
      in C, I get different results from if I try
      encodeUInt32(40966, new char[32], 32)
      in Java.

      Is this to do with C's unsigned ints and Java's long (I'm using long as I can't use unsigned ints)? If so, is there a way round it?

      Any help would be appreciated.

      Regards.

      Edited by: NegativeSpace13579 on Jun 13, 2008 2:48 AM
        • 1. Re: C to Java bit shifting/masks
          807591
          NegativeSpace13579 wrote:
          Is this to do with C's unsigned ints and Java's long (I'm using long as I can't use unsigned ints)? If so, is there a way round it?
          The workaround is to use a signed int with the >>> operator (it's THREE brackets instead of two!).
          BTW if you cast to char, you don't need the & 0xff, it's redundant. And you don't need bufsz, because an array always knows its own size.
          private int encodeUInt32(int n, char[] buf)
          {
               if (buf.length < 4) return -1;
          
               buf[0] = (char) (n >>> 24);
               buf[1] = (char) (n >>> 16);
               buf[2] = (char) (n >>>  8);
               buf[3] = (char)  n;
          
               return 4;
          }
          • 2. Re: C to Java bit shifting/masks
            807591
            and you should probably use byte not char
            and throw an exception not return -1 if the buffer length is smaller than 4.