Adding Bytes (Combining 2 x 8bits into 16bits)

Hi, I'm reading data from a text file and want two join to bytes together and read the value as an INT.

So the first byte I read is

0x02

and the 2nd byte I read is

0x58

I would like to convert 0x0258 into an int which would be 600

If I just add them together it doesn't work out because it is simply adding the digits together instead of making a longer digit. I hope this makes some kind of sense.

Here is what I have,

    byte b1 = b[15];
    byte b2 = b[16];

    println (hex(b1));
    println (hex(b2));

    numPixels = byte(b1) + byte(b2);
    println(numPixels);

I'm sure it's pretty simple but searching the web isn't getting me very far.

Thanks.

Phil

Tagged:

Answers

  • Answer ✓

    Here's one way. I'm sure you could do it with addition and bitshift operators (<<) too, but this is the most clear to me.

    byte b1 = byte(unhex("be"));
    byte b2 = byte(unhex("ef"));
    
    println (hex(b1));
    println (hex(b2));
    
    int cow = int(unhex(hex(b1) + hex(b2)));
    println(hex(cow));
    
  • That worked great, thanks

    Phil

  • Answer ✓

    Another easy way:

    byte b1 = 0x2;
    byte b2 = 0x58;
    
    int numPixels = (b1<<8) + (b2);
    println(numPixels);
    

    https://processing.org/reference/leftshift.html

    Kf

  • Excellent, thanks.

    Phil

  • edited November 2017 Answer ✓

    Like kfrajer's but will also work for negative bytes.

    int numPixels = ((b1 << 8)&0xff00) | (b2&0xff);  
    
  • Actually I get different results if I use the reply from kfrajer.

    Here is my code with the results from each method.

      byte b1 = led[15];
      byte b2 = led[16];
    
      numPixels_v1 =  (unhex(hex(b1) + hex(b2)));
      numPixels_v2 = (b1<<8) + (b2);
      numPixels_v3 = ((b1 << 8)&0xff00) | (b2&0xff);  
    
    
      println (numPixels_v1); // returns a value of 1200
      println (numPixels_v2); // returns a value of 944 
      println (numPixels_v3); // returns a value of 1200
    

    I have a solution but curious what the difference is.

    Thanks.

    Phil

  • edited November 2017 Answer ✓

    The difference happens because of negative bytes. For example -1 is 0xff as a byte but 0xffffffff as an int.
    So it you want -1 + -1 to be 0xffff, then you have to mask it.
    The + operator should work the same as the | operator as the masks don't overlap, but I switched to | just to be sure.

Sign In or Register to comment.