Hex change low to high and then conever to decimal - c#

I have Hex string like 1480D604. Which I need to change order from Low to High 0x04D68014 and then I need to cast it into decimal value. One approach that I can think is first change their order first like.
Step 1 : 14-80-D6-04 --> 04-D6-80-14
How can I change this order from Low to High order in hex value.
Step 2
Cast output from first step into decimal value like this
int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
0x04D68014=81166356
Is there any simple way to achieve this in single step.

The only way to do it in a "single step" is to define a method, use the BitConverter:
public static int ReverseByteOrder(int value)
{
byte[] bytes = BitConverter.GetBytes(value);
Array.Reverse(bytes);
return BitConverter.ToInt32(bytes, 0);
}
Usage:
int value = 0x1480D604; //or parse from string
int decValue = ReverseByteOrder(value);
//decValue = 0x04D68014
IsLittleEndian
Strictly speaking, you should look at BitConverter.IsLittleEndian as it is possible that the order is already in the correct order, depending on the system it's running on.
This is very unlikely, so I wouldn't bother coding to that case, but I would at the very least cause the program to fall over if run on a system where BitConverter.IsLittleEndian is not true.

You can do it by reversing a byte array. So first convert your string to byte array with this method:
public 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;
}
Use like:
string hexString = "1480D604";
byte[] byteArray = StringToByteArray(hexString);
Then reverse the byte array:
Array.Reverse(byteArray);
Then convert it back to hex string again with the method:
public static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
Using like:
string reversedString = ByteArrayToString(byteArray);
And finally convert it to int as you mentioned:
int decValue = int.Parse(reversedString, System.Globalization.NumberStyles.HexNumber);
And that's it. Hope it helps.

Related

Unicode Hex String to String

I have a unicode string like this:
0030003100320033
Which should turn into 0123.
This is a simple case of 0123 string, but there are some string and unicode chars as well. How can I turn this type of unicode hex string to string in C#?
For normal US charset, first part is always 00, so 0031 is "1" in ASCII, 0032 is "2" and so on.
When its actual unicode char, like Arabic and Chinese, first part is not 00, for instance for Arabic its 06XX, like 0663.
I need to be able to turn this type of Hex string into C# decimal string.
There are several encodings that can represent Unicode, of which UTF-8 is today's de facto standard. However, your example is actually a string representation of UTF-16 using the big-endian byte order. You can convert your hex string back into bytes, then use Encoding.BigEndianUnicode to decode this:
public static void Main()
{
var bytes = StringToByteArray("0030003100320033");
var decoded = System.Text.Encoding.BigEndianUnicode.GetString(bytes);
Console.WriteLine(decoded); // gives "0123"
}
// https://stackoverflow.com/a/311179/1149773
public static byte[] StringToByteArray(string hex)
{
byte[] bytes = new byte[hex.Length / 2];
for (int i = 0; i < hex.Length; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
Since Char in .NET represents a UTF-16 code unit, this answer should give identical results to Slai's, including for surrogate pairs.
Shorter less efficient alternative:
Regex.Replace("0030003100320033", "....", m => (char)Convert.ToInt32(m + "", 16) + "");
You should try this solution
public static void Main()
{
string hexString = "0030003100320033"; //Hexa pair numeric values
//string hexStrWithDash = "00-30-00-31-00-32-00-33"; //Hexa pair numeric values separated by dashed. This occurs using BitConverter.ToString()
byte[] data = ParseHex(hexString);
string result = System.Text.Encoding.BigEndianUnicode.GetString(data);
Console.Write("Data: {0}", result);
}
public static byte[] ParseHex(string hexString)
{
hexString = hexString.Replace("-", "");
byte[] output = new byte[hexString.Length / 2];
for (int i = 0; i < output.Length; i++)
{
output[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
}
return output;
}

How to convert a binary file to a string of zeroes and ones, and vice versa

I'm new to C# binary and I need to know something...
Read the exe
Translate it to string (eg. 10001011)
Modify the string
write it back to a new exe
I heard something about string.Join to convert binary to the string, but I couldn't understand very well.
To get the exe to a binary string, first read it into a byte array:
byte[] fileBytes = File.ReadAllBytes(inputFilename);
Then:
public static string ToBinaryString(byte[] array)
{
var s = new StringBuilder();
foreach (byte b in array)
s.Append(Convert.ToString(b, 2));
return s.ToString();
}
will get it to a binary string.
To turn your binary string back into a byte array:
public static byte[] FromBinaryString(string s)
{
int count = s.Length / 8;
var b = new byte[count];
for (int i = 0; i < count ; i++)
b[i] = Convert.ToByte(s.Substring(i * 8, 8), 2);
return b;
}
Finally, write the file:
File.WriteAllBytes(path, fileBytes);

Dotnet Hex string to Java

Have a problem, much like this post: How to read a .NET Guid into a Java UUID.
Except, from a remote svc I get a hex str formatted like this: ABCDEFGH-IJKL-MNOP-QRST-123456.
I need to match the GUID.ToByteArray() generated .net byte array GH-EF-CD-AB-KL-IJ-OP-MN- QR- ST-12-34-56 in Java for hashing purposes.
I'm kinda at a loss as to how to parse this. Do I cut off the QRST-123456 part and perhaps use something like the Commons IO EndianUtils on the other part, then stitch the 2 arrays back together as well? Seems way too complicated.
I can rearrange the string, but I shouldn't have to do any of these. Mr. Google doesn't wanna help me neither..
BTW, what is the logic in Little Endian land that keeps those last 6 char unchanged?
Yes, for reference, here's what I've done {sorry for 'answer', but had trouble formatting it properly in comment}:
String s = "3C0EA2F3-B3A0-8FB0-23F0-9F36DEAA3F7E";
String[] splitz = s.split("-");
String rebuilt = "";
for (int i = 0; i < 3; i++) {
// Split into 2 char chunks. '..' = nbr of chars in chunks
String[] parts = splitz[i].split("(?<=\\G..)");
for (int k = parts.length -1; k >=0; k--) {
rebuilt += parts[k];
}
}
rebuilt += splitz[3]+splitz[4];
I know, it's hacky, but it'll do for testing.
Make it into a byte[] and skip the first 3 bytes:
package guid;
import java.util.Arrays;
public class GuidConvert {
static byte[] convertUuidToBytes(String guid) {
String hexdigits = guid.replaceAll("-", "");
byte[] bytes = new byte[hexdigits.length()/2];
for (int i = 0; i < bytes.length; i++) {
int x = Integer.parseInt(hexdigits.substring(i*2, (i+1)*2), 16);
bytes[i] = (byte) x;
}
return bytes;
}
static String bytesToHexString(byte[] bytes) {
StringBuilder buf = new StringBuilder();
for (byte b : bytes) {
int i = b >= 0 ? b : (int) b + 256;
buf.append(Integer.toHexString(i / 16));
buf.append(Integer.toHexString(i % 16));
}
return buf.toString();
}
public static void main(String[] args) {
String guid = "3C0EA2F3-B3A0-8FB0-23F0-9F36DEAA3F7E";
byte[] bytes = convertUuidToBytes(guid);
System.err.println("GUID = "+ guid);
System.err.println("bytes = "+ bytesToHexString(bytes));
byte[] tail = Arrays.copyOfRange(bytes, 3, bytes.length);
System.err.println("tail = "+ bytesToHexString(tail));
}
}
The last group of 6 bytes is not reversed because it is an array of bytes. The first four groups are reversed because they are a four-byte integer followed by three two-byte integers.

How to convert an int[,] to byte[] in C#

How to convert an int[,] to byte[] in C#?
Some code will be appreciated
EDIT:
I need a function to perform the following:
byte[] FuncName (int[,] Input)
Since there is very little detail in your question, I can only guess what you're trying to do... Assuming you want to "flatten" a 2D array of ints into a 1D array of bytes, you can do something like that :
byte[] Flatten(int[,] input)
{
return input.Cast<int>().Select(i => (byte)i).ToArray();
}
Note the call to Cast : that's because multidimensional arrays implement IEnumerable but not IEnumerable<T>
It seem that you are writing the types wrong, but here is what you might be looking for:
byte[] FuncName (int[,] input)
{
byte[] byteArray = new byte[input.Length];
int idx = 0;
foreach (int v in input) {
byteArray[idx++] = (byte)v;
}
return byteArray;
}
Here's an implementation that assumes you are attempting serialization; no idea if this is what you want, though; it prefixes the dimensions, then each cell using basic encoding:
public byte[] Encode(int[,] input)
{
int d0 = input.GetLength(0), d1 = input.GetLength(1);
byte[] raw = new byte[((d0 * d1) + 2) * 4];
Buffer.BlockCopy(BitConverter.GetBytes(d0), 0, raw, 0, 4);
Buffer.BlockCopy(BitConverter.GetBytes(d1), 0, raw, 4, 4);
int offset = 8;
for(int i0 = 0 ; i0 < d0 ; i0++)
for (int i1 = 0; i1 < d1; i1++)
{
Buffer.BlockCopy(BitConverter.GetBytes(input[i0,i1]), 0,
raw, offset, 4);
offset += 4;
}
return raw;
}
The BitConverter converts primitive types to byte arrays:
byte[] myByteArray = System.BitConverter.GetBytes(myInt);
You appear to want a 2 dimensional array of ints to be converted to bytes. Combine the BitConverter with the requisite loop construct (e.g foreach) and whatever logic you want to combine the array dimensions.

Writing values to the registry with C#

I'm in the process of creating a C# application which will monitor changes made to the registry and write them back to the registry next time the user logs on.
So far I've got it monitoring changes, reporting them, writing the hive, key and value to a text file. I'm now at the point where I need to take them values out of the file and place them back into the registry. Now I've looked at various tutorials but none have been able to answer the question/problem I have, so for example the registry key I wish to change is:
HKEY_USERS\S-1-5-21-2055990625-1247778217-514451997-41655\Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\Outlook\0a0d020000000000c000000000000046 the value of 01020402 and the contents contained within that
What I want to be able to do is write back to that and change the value as appropriate. I currently have 3 strings, one contains the key location, one the value and the final is the contents of the value, although I could easily change the string manipulation to get and not get whatever I need or don't need. So if someone could provide me with a way to write to that it would be appreciated.
P.S so you know, that paticular value is a binary value that I converted to string for storage. If you require any further information please let me know.
Any help would be appreciated....thanks
EDIT Code I'm currently using:
public class reg
{
public void write(string key, string valueName, string value)
{
Byte[] byteValue = System.Text.Encoding.UTF8.GetBytes(value);
Registry.SetValue(key, valueName, value, RegistryValueKind.Binary);
}
}
I'm guessing you just need to find the right class to use to write to the registry. Using this class makes it relatively simple. Is this all you're looking for?
string key = #"HKEY_CLASSES_ROOT\.sgdk2";
string valueName = string.Empty; // "(Default)" value
string value = "sgdk2file";
Microsoft.Win32.Registry.SetValue(key,valueName, value,
Microsoft.Win32.RegistryValueKind.String);
To convert a hex string into binary data:
static byte[] HexToBin(string hex)
{
var result = new byte[hex.Length/2];
for (int i = 0; i < hex.Length; i += 2)
{
result[i / 2] = byte.Parse(hex.Substring(i, 2), System.Globalization.NumberStyles.HexNumber);
}
return result;
}
If you need to see these bytes as hexadecimal again, you can use code like this:
static string BytesToHex(byte[] bytes)
{
System.Text.StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
sb.Append(bytes[i].ToString("x2"));
}
return sb.ToString();
}
As this code demonstrates, the bytes represented as hex 0e, ff and 10 get converted to binary 00001110, 11111111 and 00010000 respectively.
static void Main(string[] args)
{
byte[] bytes = HexToBin("0eff10");
Console.WriteLine(BytesToBinaryString(bytes));
}
static byte[] HexToBin(string hex)
{
var result = new byte[hex.Length / 2];
for (int i = 0; i < hex.Length; i += 2)
{
result[i / 2] = byte.Parse(hex.Substring(i, 2), System.Globalization.NumberStyles.HexNumber);
}
return result;
}
static string BytesToBinaryString(byte[] bytes)
{
var ba = new System.Collections.BitArray(bytes);
System.Text.StringBuilder sb = new StringBuilder();
for (int i = 0; i < ba.Length; i++)
{
int byteStart = (i / 8) * 8;
int bit = 7 - i % 8;
sb.Append(ba[byteStart + bit] ? '1' : '0');
if (i % 8 == 7)
sb.Append(' ');
}
return sb.ToString();
}
So you have a string that you need to convert to binary and write to the registry? Does this work?
string valueString = "this is my test string";
byte[] value = System.Text.Encoding.ASCII.GetBytes(valueString);
Microsoft.Win32.Registry.SetValue(keyName, valueName, valueString, Microsoft.Win32.RegistryValueKind.Binary);

Categories