Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise operation in ActionScript 3 compare to Java

I am researching this AS3 code that write a BitString into a ByteArray. Source: JPGEncoder#writeBits()

private var byteout:ByteArray;
private var bytenew:int = 0;
private var bytepos:int = 7;

private function writeBits(bs:BitString):void
{
    var value:int = bs.val;
    var posval:int = bs.len-1;
    while (posval >= 0) {
        if (value & uint(1 << posval)) {
            bytenew |= uint(1 << bytepos);
        }
        posval--;
        bytepos--;
        if (bytepos < 0) {
            if (bytenew == 0xFF) {
                writeByte(0xFF);
                writeByte(0);
            } else {
                writeByte(bytenew);
            }
            bytepos=7;
            bytenew=0;
        }
    }
}

But I don't understand part of the code.

  • What is uint(1 << bytepos)?
  • What is the if condition if (value & uint(1 << posval))?
    • I don't know whether the & is "and" bit operator, or "and" condition.
    • Does if(number) in AS3 means if(number != 0) ?

What is these AS3 code equivalent in Java?

like image 626
nhoxbypass Avatar asked Feb 11 '26 02:02

nhoxbypass


1 Answers

Bitwise operations in Java are somewhat awkward, because Java has no unsigned types. So when you intend to work with bytes, you should make sure you stay with bytes. Things like 0x0f | 0x80 -> 0b1000 1111 done with bytes must be cast to bytes all the time:

System.out.printf("%x - %x - (byte)%x - (int)%x\n", 
                   (byte)0x80, 
                   (byte)0xf, 
                   (byte)((byte)0x80|(byte)0xf), 
                    (int)((byte)0x80|(byte)0xf));

OUTPUT:
80 - f - (byte)8f - (int)ffffff8f

Having said this, you may want to work with ints from the beginning and cast to bytes later.

The code you present transcribes the BitString into a bit stream cut into bytes.

A special case is handled if all bits of a byte are set, in that case 0xff00 is output.

What is uint(1 << bytepos)?

This moves the lhs of the operator by bytepos bits to the left:

1 << 4 -> 0b00010000

What is the if condition if (value & uint(1 << posval))? I don't know whether the & is "and" bit operator, or "and" condition.

& is bitwise AND, && is boolean.

The operation is != 0 -> TRUE if the bit at posval position is set. This is the condition to set the corresponding bit in the byte.

Transferring the code to Java should be straightforward actually. I would suggest you use plain int in java and convert to byte just before you write:

byte realByte = (byte)(intbyte & (byte)0xff);
writeByte(realByte);

This way, you avoid constant casting to byte and you avoid the above mentioned problem with negative bytes.

like image 84
thst Avatar answered Feb 16 '26 08:02

thst



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!