Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bit operations in c

how do you reverse and rotate hex numbers and return the number in C with bitwise operators?

for example:

0xabcd -> 0xdcba

0xabcd -> 0xdabc
like image 724
SuperString Avatar asked Dec 13 '22 00:12

SuperString


2 Answers

It's hard to know where to begin with this question. Plus I smell homework.

Some points:

  • There is no such thing as a "hex number". Hex is just a notation. How do you reverse and rotate decimal numbers and return the number in C? For example:

    1776 -> 6771

    1776 -> 6771?

  • To solve this problem, you need a deep understanding of positional notation, whether it's base 10, base 16, base 2, or what have you.

  • All you need can be had by adding, subtracting, multiplying, and dividing. Those are operations on numbers. Modulus is also very helpful.

  • If you happen to want to multiply or divide by a power of two, I commend to you the C left shift << and right shift >> operators. These work perfectly for numbers that are represented using the C types unsigned or unsigned long.

like image 194
Norman Ramsey Avatar answered Dec 23 '22 14:12

Norman Ramsey


Hex numbers are numbers, as Norman's answer points out. However, 1 hex digit = 4 bits, so these operations actually make sense as things you could possibly want to do to integer values.

The 2nd one is a bitwise rotation by 4 bits. See Best practices for circular shift (rotate) operations in C++ for best practices for compiler-friendly rotates that guard against C/C++ undefined-behaviour.

If your input isn't 8, 16, 32, or 64 bits, then you might need to shift + mask manually, instead of relying on shift-in-zeroes.


The first one will require more code: it reverses the order of the nibbles. There is no machine instruction for that, or easy way to build it out of a few bitwise operations on the entire number at once.

I think you'd have to reverse the order of the bytes, and then reverse the order of nibbles within each byte (an 8-bit rotate by 4).

like image 25
Peter Cordes Avatar answered Dec 23 '22 15:12

Peter Cordes