Click here to Skip to main content
15,881,938 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hello everyone,

I need your help because I’m blocking this part of my code...

I’d like to divide each HEX into a string

For example String hex = " 1A14"
to have String divideHex = "0D0A"

Because hex 1A/2 = 0D and hex 14/2 = 0A

An idea ? Thank you to those who will help me!!


EDIT: Thank you all for your help!! Thanks to you I adapted my code: I no longer divide after having opened my file and converted my file to HEX but directly upon opening it!

What gives in code it can help beginners like me:
C#
var fileContent = string.Empty;
var filePath = string.Empty;
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
    openFileDialog.InitialDirectory = "%userprofile%";
    openFileDialog.Filter = "bin files (*.bin)|*.bin";
    openFileDialog.FilterIndex = 2;
    openFileDialog.RestoreDirectory = true;
    if (openFileDialog.ShowDialog() == DialogResult.OK)
{
filePath = openFileDialog.FileName;
var fileStream = openFileDialog.OpenFile();
byte[] readBytes = File.ReadAllBytes(filePath);
for (var i = 0; i < readBytes.Length; i++)
{
    readBytes[i] /= 2;
}
foreach (byte s in readBytes)
{
    Console.WriteLine(s);
}
byte[] data = readBytes;
string hex = BitConverter.ToString(data).Replace("-", string.Empty);


Then I modify the code to extract some parts:
C#
int pFrom = hex.IndexOf("2A60602A");
int pStart = hex.IndexOf("23322931342B391E18181805") + "23322931342B391E18181805".Length;
int pTo = hex.LastIndexOf("2A4560602A") + "2A4560602A".Length;
string startCode = hex.Substring(pStart, pFrom - pStart);
string endCode = hex.Substring(pTo);
string newCode = startCode + endCode;


And I converted to BYTES to save to a new file:
C#
int numberCharsCode = newCode.Length;
byte[] newCodeBytes = new byte[numberCharsCode / 2];
for (int w = 0; w < numberCharsCode; w += 2)
{
     newCodeBytes[w / 2] = Convert.ToByte(newCode.Substring(w, 2), 16);
}
string newFilePath = filePath.Replace(".bin", "_decrypted.usp");
File.WriteAllBytes(newFilePath, newCodeBytes);


So far everything works perfectly! I still have a few questions for you experts:
- Is it possible to make it simpler?
"Do you see mistakes or illogical things?"
- Is it possible to extract the desired parts in BYTES in order to avoid unnecessary conversion and weighing down the code?

But! For there is always a but! After executing this code on a file I notice that there is a second level of encoding that reacts in 2 different ways depending on the start and end delimiter! Let me explain.
For the code contained in the delimiters 5E54/545E (5E54"CODE EN HEX"545E) or 5E5E/1A14: in this example C2 (in HEX) = a (in ASCII) but this applies to all the HEX that define a characteristic and that follow each other!
- a = C2
- aa = 3C643AC23E
- aaa = 3C643AC23E
- aaaa = 3C663AC23E
- aaaaa = 3C683AC23E
- aaaaaa = 3C6A3AC23E
- aaaaaaa = 3C6C3AC23E
- aaaaaaaa = 3C6E3AC23E
- aaaaaaaaa = 3C703AC23E
- aaaaaaaaaa = 3C723AC23E
- aaaaaaaaaaa (10) = 3C62603AC23E
- aaaaaaaaaaaa = 3C62623AC23E
- aaaaaaaaaaaaaaaaaaaaaa (20) = 3C64603AC23E
- aaa... (100) = 3C6260603AC23E (guess)
And for codes not contained in this delimiter:
- a = C2
- aa = C2C2
- aaa = 3C643AC23E
- ...

I specify that this example is valid before having divided by 2 the BYTES, after division the set of HEX is divided by 2 (C2 = 61 ; 3C = 1E ; ...)

So, since I start in C# this part becomes extremely complicated for me! So let me ask you a few questions before I start without knowing where I’m going: how? Do you have any leads on what I should use to do this? and the simplest method in your opinion?

Thank you in advance for your contribution!

Maybe I need to create a new question for that?

What I have tried:

I tried many things but unfortunately I can’t find help on the net that explains this problem
Posted
Updated 28-Jan-23 0:52am
v3
Comments
0x01AA 26-Jan-23 17:19pm    
And what should be the result in case src= '0303'?
Btw, makes sense you show your code.
Ralf Meier 26-Jan-23 18:04pm    
without understanding the sense of your question :
- take the Byte-Part (for example 1A) from the string
- build an integer-value from it
- divide it by 2 or do a shift right
- rebuild a string-value from the new byte-value

How you do this depends on exactly what you are trying to do: your description suggests that you want to divide each byte by two, so "0101" would give "0000" because the "spare bit" at the bottom of each byte value would be discarded.
Alternatively, should "0101" become "0080", or "008080" as the "bottom bit" of each byte is propagated down through the data?

The second one is simple:
C#
int intValue = int.Parse("0101", System.Globalization.NumberStyles.HexNumber);
converts the hex string to an integer, you can easily divide that, and convert the result to a string again with ToString:
C#
string result = (intValue / 2).ToString("X4");
But you'll have to append the final bit value yourself - it is trivial.

The first one is harder: write a method to convert a hex character to a hex value byte, then pull two characters out of the string and convert them to a single byte:
C#
byte value = (byte) (Convert(hexString[0]) * 16 + Convert(hexString[1]));
then you can divide and convert back to a string similar to above.
 
Share this answer
 
You may use the Convert class:
C#
string s = "1A14";
var a = Convert.FromHexString(s);
for (int n=0; n<a.Length; ++n)
   a[n] /= 2;
s = Convert.ToHexString(a);
 
Share this answer
 
Comments
Joan FUHRMANN 27-Jan-23 2:58am    
I think this solution is the right one! However I have an error: 'convert' does not contain a definition for 'FromHexString'! Why? I’m sorry I started on C#!
CPallini 27-Jan-23 3:52am    
Possibly because you are using an older version of the framework. Such methods came with .NET 5.
This: applies only to Integers, not floating point values; issues if international string syntax are not considered.

See this for how to convert a hex string to an integer: [^] ... note that two different techniques are shown for handling two forms of hex string syntax.

Divide the integer by the integer divisor, then convert the resulting integer to a hex string:string hexInt = someInt.ToString("X"):Note: you nay have to deal with issues of string padding,
 
Share this answer
 
static void Main()
{
   var hexa = "141A";

   // Convert to byte array from string
   var strByte = StringToByteArray(hexa);
    for (var i = 0; i < strByte.Length; i++)
    {
        strByte[i] /= 2;
    }

    // Convert to string from byteArray after dividing
    // str is the desired output
    var str = ByteArrayToString(strByte);

}

private static byte[] StringToByteArray(string hex)
{
    int NumberChars = hex.Length;
    byte[] bytes = new byte[NumberChars / 2];
    for (int i = 0; i < NumberChars; i += 2)
        bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
    return bytes;
}
private static string ByteArrayToString(byte[] byteArray)
{
    StringBuilder hexa = new StringBuilder(byteArray.Length * 2);
    foreach (byte b in byteArray)
        hexa.AppendFormat("{0:x2}", b);
    return hexa.ToString();
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900