2 Replies - 1660 Views - Last Post: 10 December 2011 - 05:00 PM Rate Topic: -----

#1 novacrazy  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 14
  • View blog
  • Posts: 117
  • Joined: 01-March 11

Bit Rotation with Carry

Posted 01 October 2011 - 08:51 PM

Description: The rotation MUST be less than __BYTE_SIZE__ amount, or results are unknown.Algorithm for rotating a variable.
/*
Description and Usage:
    Algorithm for rotating a variable.
    The rotation MUST be less than __BYTE_SIZE__ amount,
    or results are unknown
Author:
    Full Name:
        Aaron Trent
    Screen Name:
        novacrazy
Date:
    October 1st, 2011
*/
#include <stddef.h> //for NULL and size_t
//type of variable to be used, can be any unsigned integer type
#define __BYTE_TYPE__ unsigned char
#define __BYTE_SIZE__ (sizeof(__BYTE_TYPE__) * 8)
//provides a variable of __BYTE_TYPE__ that is completely full.
#define __FULL_BYTE__ ~(__BYTE_TYPE__)NULL
//rotates variable right by _f amount.
typedef __BYTE_TYPE__ b_type; //to make it look nicer

inline void rotate_right(b_type &n, size_t _f)
{
    //creates the carry by masking the parts to be carried
    register b_type carry = (n & (__FULL_BYTE__ >> _f));
    //shifts the original by the desired amount
    n >>= _f;
    //shifts the carry so it is at the location needed to be inserted back into the originial
    carry <<= (__BYTE_SIZE__ - _f);
    //inserts the carry using XOR, though I suppose it could use OR if you'd like
    n ^= carry;
}
//to rotate left, the shifts are simply reversed
inline void rotate_left(b_type &n, size_t _f)
{
    register b_type carry = (n & (__FULL_BYTE__ << _f));
    n <<= _f;
    carry >>= (__BYTE_SIZE__ - _f);
    n ^= carry;
}

//Usage
#include <stdio.h>
int main()
{
    b_type test = 3;
    //      00000011
    rotate_right(test, 1);
    // now  10000001, or 129
    printf("%i", (int)test); //prints 129
    return 0;
}


Is This A Good Question/Topic? 0
  • +

Replies To: Bit Rotation with Carry

#2 KYA  Icon User is offline

  • Wubba lubba dub dub!
  • member icon

Reputation: 3202
  • View blog
  • Posts: 19,232
  • Joined: 14-September 07

Re: Bit Rotation with Carry

Posted 10 December 2011 - 04:48 PM

Shifts greater then byte_size (typically 8) will results in no carries when shifting, i.e. 0x01 shifted to the left 8 places will be zero since all bits are shifted out.
Was This Post Helpful? 0
  • +
  • -

#3 novacrazy  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 14
  • View blog
  • Posts: 117
  • Joined: 01-March 11

Re: Bit Rotation with Carry

Posted 10 December 2011 - 05:00 PM

I know, that's why I stated that the amount to be rotated by be less than __BYTE_SIZE__. A simple way to ensure that would be to just modulus the input _f by __BYTE_SIZE__, eg: rotate_left(x, 124%__BYTE_SIZE__);
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1