2013-04-10 6 views
7

क्या जावा में कोई अंतर्निहित फ़ंक्शन है जिसे मैं दो बिट्स को स्वैप करने के लिए उपयोग कर सकता हूं?मैं जावा में पूर्णांक के दो बिट्स कैसे स्वैप कर सकता हूं?

उदाहरण के लिए:

_ _ _ _ 1 _ _ 0 सा 3 बिट 0 के साथ बदली और हो जाता है _ _ _ _ 0 _ _ 1

मैं जानता हूँ कि यह एक लंबे समय से प्रक्रिया का उपयोग किया जा सकता है बिट-वार ऑपरेशन, लेकिन मैं ऐसा करने से बचना चाहता हूं।

+0

कितना समय है कि आप इसे नहीं होना चाहता हूँ की कोशिश कर सकते हैं? मुझे नहीं लगता कि एक अंतर्निर्मित है जो विशेष रूप से बिट्स को स्वैप करता है। – iamnotmaynard

+0

ऐसा कोई फ़ंक्शन मौजूद नहीं है – BlackJoker

+2

"बिट-वार ऑपरेशन की लंबी प्रक्रिया" जाने का तरीका है, हालांकि यह शायद इतना लंबा नहीं होगा। –

उत्तर

5

मैं विवरण में यह बना रही हूँ, लेकिन आप एक पंक्ति

int temp1 = (i & 0x1) << 3; //extract lowest bit #1 and place at pos# 4 
int temp2 = (i & 0x8) >> 3; //extract bit #4 and place at pos #1 
i = (i & temp1) | (i & ~temp1); //now pos #4 is ready  
i = (i & temp2) | (i & ~temp2); //now pos #1 is ready 
7

यहाँ एक वैकल्पिक तरीका है, एक डेल्टा-स्वैप कहा जाता है में शामिल हो सकते हैं।

int t = (i^(i >> 3)) & 1; 
return i^t^(t << 3); 

या अधिक आम तौर पर:

static int swap(int x, int i, int j) 
{ 
    // precondition: i > j 
    int d = i - j; 
    int y = (x^(x >> d)) & (1 << j); 
    return x^y^(y << d); 
} 
10

तुम भी इस तरह से

//positions are indexed from 0 and in order ...[4][3][2][1][0] 
//so changing 3 and 1 will make    ...[4][1][2][3][0] 
public static int swap(int i, int pos1, int pos2) { 

    int bit1 = (i >> pos1) & 1;// bit at pos1 
    int bit2 = (i >> pos2) & 1;// bit at pos2 

    if (bit1 == bit2) 
     return i; // no need to swap since we change 1 with 1 or 0 with 0 

    // Since we are here it means that we need to change 1->0 and 0->1. 
    // To do this we can use XOR (^). 
    // Lets create mask 000001010 with ones at specified positions 
    int mask = (1 << pos1) | (1 << pos2); 

    return i^mask;// TADAM!!! 
} 
संबंधित मुद्दे