grizeldi
grizeldi

Reputation: 180

Difficult formula

I am new to bytes and bits and I'm also not very good in maths either. I kind of understand the bitwise operators, but I don't know how to solve math equations/formulas with 2 variables. I'm not sure this is the proper place to ask this but anyway.

I have an formula like this:

(Adr_MSB & 0x3F) << (8 + Adr_LSB)

Now what I want is that I would get an integer (for example 33) and the code would transform it into Adr_MSB and Adr_LSB (which are bytes). It should work up to 128 (ok I guess it will be 127).

I know that this question might sound dumb or something, but I just don't know enough maths to solve this.

Thanks for all help.

EDIT: By experimenting I figured out, that Adr_MSB is a multiplier (e.g. if it's 10 the result is 10 times biger than if it's 1).

Upvotes: 2

Views: 229

Answers (3)

Tawcharowsky
Tawcharowsky

Reputation: 625

Would this work?

int x = 33;
byte Adr_MSB = (byte)x;
byte Adr_LSB = (byte)24;
System.out.println((Adr_MSB & 0x3F) << (8 + Adr_LSB));

Adr_LSB can also be -8.

Since you do bitwise AND on Adr_MSB and 111111, you have only six consecutive bits available to represent the number, so not all integers can be represented just by shifting those 6 bits. This solution works for x up to enter image description here, so... you can argue that is not a good solution, but it is a start.

Upvotes: 0

shanmuga
shanmuga

Reputation: 4499

From what I understand

  • the (Adr_MSB & 0x3F) part of the takes the last six bits of the Adr_MSB and returns corresponding integer.
    • Eg: 125 (1111101) will return 61 (111101)
    • Note: This step is removing all bits other than last 6 bits, these bits are lost. Hence Lossless inverse function is not possible.
  • The (8 + Adr_LSB) just adds 8 to Adr_LSB.
  • << is a bit wise Left Shift Operator.
    • Eg. 61 << 3 = 488 . Since 61 is 111101, adding three zeros to the right (Left Shifting three times) will give 111101000 which is 488.

Effective inverse of the expression (Adr_MSB & 0x3F) << (8 + Adr_LSB) to be applied to given number x

  1. Take first six bits from x and convert it to int. This will be Adr_MSB.
  2. Count the rest of the bits. Subtract 8 from this count and it will be Adr_LSB.

Upvotes: 1

WestCoastProjects
WestCoastProjects

Reputation: 63221

Does the following represent what you are looking for?

((Adr_MSB & 0x3F) << 8) | Adr_LSB

Upvotes: 0

Related Questions