0

Hi I'm trying to do something which should be simple, but I can't figure it out. I have a pointer to an array of unsigned chars, and I get the first element, which is a hex number. I want to convert it to binary so I can check if it's equal to a number such as 0x01101000.

      unsigned char arr[] = {0x25};  //just for example. I am actually using *arr.
      unsigned char byte = arr[0];
      if(( byte & 0x01101000) == //not sure if this is the right way to proceed

Would appreciate some help! Thanks!!

Piotr Chojnacki
  • 6,837
  • 5
  • 34
  • 65
user2057841
  • 213
  • 1
  • 4
  • 14
  • 1
    The C language has no construct to express binary literals. Also, all numbers in a computer are binary in the end, which means that just comparing any two integers actually are comparing two binary numbers. – Some programmer dude Feb 10 '13 at 18:41
  • `0x01101000` is a hexadecimal number, you do know that? The binary representation would be `1000100000001000000000000`. – Luchian Grigore Feb 10 '13 at 18:42
  • Numbers are all in binary, whatever kind of literal you use. Do you really want to build a number whose hexadecimal representation would give 25 if misinterpreted as binary? – Anton Kovalenko Feb 10 '13 at 18:42
  • Oops, I'm not looking for binary. I guess I just want to compare 2 hex numbers then? In that case, will if(byte == 0x01101000) give me the correct result? – user2057841 Feb 10 '13 at 18:43
  • You'll have to do the conversion by hand. Make a function for that. – Afonso Tsukamoto Feb 10 '13 at 18:44
  • In my example, when I print byte using printf("%02x\n ", byte); it prints 25. – user2057841 Feb 10 '13 at 18:44
  • If you want to check if the value is equal to the binary number 01101000 , just convert it to hex and do if (whatever == 0x68) – nos Feb 10 '13 at 21:17

1 Answers1

1

See this answer.

If you are using GCC then you can use GCC extension for this: int x = 0b00010000;

So in your case, it would be:

if( byte == 0b01101000 )
...

Be sure to put only 8 bits in your literal though.

Community
  • 1
  • 1
JosephH
  • 8,465
  • 4
  • 34
  • 62
  • Thanks. Can I use == to check for equality? – user2057841 Feb 10 '13 at 18:46
  • @user2057841 fixed it. Different operators serve different purposes. Refer to http://stackoverflow.com/a/6092250/762123 for more details on bitwise operators. – JosephH Feb 10 '13 at 18:49
  • @user2057841, you'd be better off using hex notation inside your program, it will be more portable. The 0b notation will only be useful when using GCC. – Josh Petitt Feb 10 '13 at 21:16