Link to home
Start Free TrialLog in
Avatar of BullfrogSoftware
BullfrogSoftwareFlag for United States of America

asked on

Given 3 Bytes of Data - How to convert to 6 digit ID code?

I am given 3 bytes defined as:

MSB_ID
ID
LSB_ID

Obviously, MSB and LSB stand for Most Significant Byte and Least Significant Byte.

How can I derive a 6-digit integer ID code from this in C#?

I have a similar operation in the program that calculates from just an MSB and an LSB to get a resultant integer:

int timer = Convert.ToInt32(msb, 16) << 8 | Convert.ToInt32(lsb, 16);

Open in new window


However, with the added 'middle' byte, I am a bit lost.
Avatar of d-glitch
d-glitch
Flag of United States of America image

The formula to convert three bytes (24 bits) to binary is:

          MSB_iD*256 ²  +  MID_ID*256  +  LSB_ID
Avatar of BullfrogSoftware

ASKER

To binary?  I am looking for a 6-digit id code, such as '123456' .. to be derived from the 3 given bytes.
ASKER CERTIFIED SOLUTION
Avatar of d-glitch
d-glitch
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You can't guarantee to be able to do it for all possible ids using only digits.
With three bytes, there are 16777216 different possible IDs. So you would need 8 digits unless you knew something special about the data (like MSB_ID is only ever 1-50).
If you want a 6 character hex number (0-9 and A-F), then that would work for three bytes.

If neither of the above apply, it is literally impossible. The other thing you could do (possibly) is just assign IDs and keep a mapping somewhere. But there is no way to guarantee a unique six digit decimal number for three bytes.
An error in the first comment:

     The formula to convert three bytes (24 bits) to decimal is ....
To convert a byte into two hex digits you do an integer division by 16 and take the quotient and the remainder.
Does it matter what 6 digits you get out of what MSB_ID ID LSB_ID values?
If so, can you give us an example of the conversion you want?
I will actually close this question.  What the customer wanted was as follows:

3 bytes given, convert bytes to strings, concatenate to create hex string, convert string to int

string hexVal = msb + b + lsb;
int i = Convert.ToInt32(hexVal, 16);

Open in new window


It was that simple.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I mentioned before the code "convert bytes to strings" ... this takes place before they are passed to the code above.
So you were saying that the conversion happened before your code. Got it. Glad you got it working.