'How can I write bytes with -? [closed]

I want to make a checksum but I need to know the last string which is written as UTF and is also then compressed. I am writing these bytes into a C# MemoryStream.

I can't decompress it because I can't write C# bytes with a minus sign - (eg: a -16 or -56).

Can someone help?

ActionScript (Flash) code:

var loc1:ByteArray = new ByteArray();
         loc1.writeByte(120);
         loc1.writeByte(-38);
         loc1.writeByte(99);
         loc1.writeByte(16);
         loc1.writeByte(12);
         loc1.writeByte(51);
         loc1.writeByte(41);
         loc1.writeByte(-118);
         loc1.writeByte(12);
         loc1.writeByte(50);
         loc1.writeByte(81);
         loc1.writeByte(73);
         loc1.writeByte(49);
         loc1.writeByte(-56);
         loc1.writeByte(13);
         loc1.writeByte(48);
         loc1.writeByte(54);
         loc1.writeByte(54);
         loc1.writeByte(14);
         loc1.writeByte(48);
         loc1.writeByte(46);
         loc1.writeByte(2);
         loc1.writeByte(0);
         loc1.writeByte(45);
         loc1.writeByte(-30);
         loc1.writeByte(4);
         loc1.writeByte(-16);
         loc1.uncompress();
         loc1.position = 0;
         return loc1.readUTF();
    
    


Solution 1:[1]

For situations where the single byte is signed with a minus sign:

You can try: myBytes[ somePosition ] = ( 256 + (-X) ); //where -X is your signed value.

Looking at first two bytes:

AS3 code:

loc1.writeByte(120); //is 0x78
loc1.writeByte(-38); //is 0xDA

The second byte has -38 so doing a (256 + (-38) gives you byte 0xDA.
(where 0xDA has a "unsigned" value of 218 or alternatively is a "signed" value of -38).

C# code:

memStream.WriteByte( 120 );  //writes 0x78
memStream.WriteByte( (256 + (-38)) ); //writes 0xDA

So the first two bytes are hex values of: 0x78DA.

Funnily enough I've seen this before in a ZLIB header. This is what loc1.uncompress(); is doing, passing the byte array to a ZLIB decompressor. After decompressing you'll get bytes that represent a UTF String (one byte per String's characters).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1