I am trying to replicate the following Java code in JavaScript that will set a Bit in a byte[]
.
The Java Class has two private method functions to set a bit and check if a bit is set.
private boolean isBitSet(byte b, int pos) {
byte test = 0;
return (setBit(test, pos) & b) > 0;
}
private byte setBit(byte b, int pos) {
return (byte) (b | (1 << pos));
}
The byte[] payload
has a length of 80 with the last 13 empty and setBit
is called on the last byte as follows:
payload[79] = setBit(payload[79], 0);
The whole payload is then Base58check encoded
The JavaScript looks like this:
const payload = new Uint8Array(80);// Buffer.alloc(80, 0) for node
payload[79] = setBit(payload[79], 0)
What I have tried:
Setting it to 128 (0b10000000
) but I realised that would be the last Bit.
Setting it to 1 (0b00000001
)
Setting it to 2, 4, 8, 16, 32, 64.
Setting using bitwise and assignment operators from this answer: payload[79] |= 1 << 0
Using an online Java to JS converter:
const setBit = (byte, pos) => ((byte | (1 << pos)) | 0);
How I know none of these worked:
After running both payloads through a (definitely equivalent) base58check.encode function, only the last few characters are different, representing the last byte and the checksum.
Other help I have sought:
I have asked for help from the Java code developer and was told regarding signed/unsigned that “We treat the values as unsigned. Java doesn’t have unsigned byte so the values are integers cast to bytes : val = (byte)0xFF (for example). You might have to check on the endianness in your implementation. Java uses big endian as the default.” What I understand about endians is that it is about the order that bytes are written to memory and so I thought that it wouldn’t matter for a single Byte.
Question:
Please help me to find a solution? I would like to understand where I went wrong.
Thanks