-1

I have number "000001B6" (hexadecimal). I want to convert hex "000001B6" to integer or byte, then search result number in array of byte to check if this number exists in array or not.

How can i do that in C#, such that:

byte[] temp = new byte[20];

number = 000001B6 // convert number to integer or byte then search result number in array 
Robert Gannon
  • 253
  • 4
  • 13
  • 2
    this [question](http://stackoverflow.com/questions/74148/how-to-convert-numbers-between-hexadecimal-and-decimal-in-c) could solve your problem – Tinwor Oct 21 '13 at 20:41
  • 6
    `0x1B6` (1B6_16 or 438_10) is larger than `byte.MaxValue` (FF_16 or 255_10). How would such a value be encoded in your `byte[]`? – Tim S. Oct 21 '13 at 20:45

2 Answers2

0

Try this to convert the hexadecimal number to integer

string hexNumber = "000001B6";
int integerValue = int.Parse(hexNumber, System.Globalization.NumberStyles.HexNumber);

You can only search for 255 as it is the maximum value for the byte[], so you must be sure that you hexadecimal number should not be more than that.

But you example string ie. 00001B6 is equivalent to 438. So you need to take care of the Range.

Otherwise you can simple use .Any function to check the existence inside the array.

bool isExists = temp.Any(x => x == integerValue);
Sachin
  • 40,216
  • 7
  • 90
  • 102
  • ok thanks...but array of byte not contain definition of contains?? – user2898387 Oct 21 '13 at 21:01
  • @user2898387 use `.Any`. See my update in my answer and let me if any problem found. – Sachin Oct 21 '13 at 21:11
  • Use `int integerValue = 0x1B6;` if this is a literal. There's no point in changing from `Contains` to `Any`. Both are Linq extension methods. Neither exist on `byte[]`, but both will be in scope with a `using System.Linq;` directive. – Jeppe Stig Nielsen Oct 21 '13 at 21:17
0
byte[] temp = new byte[20];
var i = int.Parse("000001B6", System.Globalization.NumberStyles.HexNumber); //438
if(i <= byte.MaxValue) //will never be true for 000001B6 since 438 > 255
    var hasValue = temp.Contains((byte)i);
Magnus
  • 45,362
  • 8
  • 80
  • 118
  • Why not simply `temp.Contains(0x1B6)`? Why did you change to an `int[]`? Was that what the asker wanted? – Jeppe Stig Nielsen Oct 21 '13 at 21:15
  • @JeppeStigNielsen the hex value is in a string format hence the parse. Also `0x1B6` is larger than what can fit into a `byte`. – Magnus Oct 21 '13 at 21:21
  • Then you should explain that in your answer. The question seemed to talk about an array of bytes. Certainly `0x1B6` is the same as `int.Parse("000001B6", System.Globalization.NumberStyles.HexNumber)`, and since it has three hex digits, it will need a `short` or something wider. I just think your answer should elaborate on that. Otherwise it is not actually an answer. – Jeppe Stig Nielsen Oct 21 '13 at 21:25
  • @JeppeStigNielsen Sure I'll try to make it more clear. – Magnus Oct 21 '13 at 21:37