Search code examples
c#javac++bit-manipulationshift

Converting a string in a hexa with 21 chars


I have a service to integrate with another application, and it accept just 21 hexa chars. I need to pass and recieve a string with 11 decimal chars, for sample: String s = "0101230154V";

I would like to know, how could I use the shift operations to convert it in bits and transmit, because I cannot convert my decimal string to hexa because it will result in 22 hexa chars. I have tried with the code bellow. I think it is ok the hexa conversion, but when I have tried to convert back to decimal notation it does not work, give me other values. Programmers C#, C++ and Java I think could help me.

int n = 99;  // 2^6 bits to use 99
int k = 999; // 2^9 bits to use 999

int bits = (n << 6) | (k << 9 << 6); // I'm not sure if it is ok to convert and use with hexa

var hexa = bits.ToString("X"); // I will transmit this hexa to a web service

And in a another project, I have a Windows Service to read the hexa from the web service. I can read fine but I do not know how to convert back the hexa value and take the n and k values, for sample:

string hexa = GetFromWebService(); // get from the value from the web service here, its fine

// I will recieve the hexa and get the number in bits
int received = Int32.Parse(hexa, System.Globalization.NumberStyles.HexNumber);

// here I need to discover the N and K values... how?

How to discover the n and k values?

Final solution

long v = 123456789456;
string h = v.ToString("X");

// trasmit h value

var data = long.Parse(hexaValueFromService, System.Globalization.NumberStyles.HexNumber);

thank you


Solution

  • I don't know if there's a typo when you say "11 decimal characters" or not because the last character clearly is not a decimal or hexadecimal digit.

    If it's a real typo, 11 decimal characters have a maximum value of 99 999 999 999 which fits into a 64-bit int which corresponds to only 16 hex chars. So you can convert the string to int64_t (C++)/long (C#/Java) and then pass to the other service.

    In case that it's not a typo then you can still convert the first 10 decimal digits to a int64_t and then pass both the int64_t and the remaining character, only 18 hex chars is needed

    If you don't want to convert to binary then densely packed decimal (DPD) is a good choice. It packs 3 decimal digits into 10 bits. So 10 digits need 34 bits which takes up 9 hex digits. This works directly on decimal and doesn't need to convert into binary so not only it takes up less space but it's also very quick in conversion back and forth. If you don't need to do arithmetic on the value, this maybe the best choice