Increment of hex values from a byte
-
Hi.
I'm trying to increment a hex value but I can't find a working solution.
I've got a Byte Array and I want to increment on special byte of it, for example:
bytearray[5]
I'm not sure how to handle this in C#.
Normaly it should work somehow like converting the byte into a hex value and then incement this hex value.
Can someone help me?
Greeting,
TheBullP.S. Sorry for my bad Endlish
-
Does your byte array represent a numeric value?
If yes, then first convert the bytes to the desired numeric value (eg. int, long, etc.) and then increment it. If needed, convert it back to your byte array.
Conversion can be done with the sift operator ( << and >> )and the bitwise or operator (|).
Simon
-
byte[] array = new byte[] { 0, 1, 2, 3, 4 }; array[2]++; foreach(byte b in array) Console.WriteLine("{0}", b); //Output: // 0 // 1 // 3 // 3 // 4
-
It's a hex value ....
I tried it his way:
// Returns hex String representation of byte b static public String byteToHex(byte b) { char [] hexDigit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9','a', 'b', 'c', 'd', 'e', 'f' }; char[] array = { hexDigit[(b >> 4) & 0x0f], hexDigit[b & 0x0f] }; return new String(array); }
That's working until the byte/hex has a letter in it like: 0x0a
Any ideas?
Greetings,
The BullByte[] Byte2 = BitConverter.GetBytes(Convert.ToByte(byteToHex(received[2]++)));
-
static string ByteToHex(byte b) { char[] hexDigit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; char[] array = { hexDigit[(b >> 4)], hexDigit[b % 16] }; return new string(array); }
-
Hello.
The functions doesn't seems to be wrong.
Byte[] Byte2 = BitConverter.GetBytes(Convert.ToByte(byteToHex(received[2]++)));
doesn't work.
As I've said before it's working fine with digits like 0x08 but it fails with letters like 0x0a.
The Exception:
System.FormatException: Input string not in correct format.
bei System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
bei System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
bei System.Byte.Parse(String s, NumberStyles style, NumberFormatInfo info)
bei System.Convert.ToByte(String value)