privatestatic String toStringUTF16(int i, int radix) { byte[] buf = newbyte[33 * 2]; boolean negative = (i < 0); int charPos = 32; if (!negative) {
i = -i;
} while (i <= -radix) {
StringUTF16.putChar(buf, charPos--, digits[-(i % radix)]);
i = i / radix;
}
StringUTF16.putChar(buf, charPos, digits[-i]);
/** *Placescharactersrepresentingtheintegeriintothe *characterarraybuf.Thecharactersareplacedinto *thebufferbackwardsstartingwiththeleastsignificant *digitatthespecifiedindex(exclusive),andworking *backwardsfromthere. * *@implNoteThismethodconvertspositiveinputsintonegative *values,tocovertheInteger.MIN_VALUEcase.Convertingotherwise *(negativetopositive)willexpose-Integer.MIN_VALUEthatoverflows *integer. * *@paramivaluetoconvert *@paramindexnextindex,aftertheleastsignificantdigit *@parambuftargetbuffer,Latin1-encoded *@returnindexofthemostsignificantdigitorminussign,ifpresent
*/ staticint getChars(int i, int index, byte[] buf) { int q, r; int charPos = index;
boolean negative = i < 0; if (!negative) {
i = -i;
}
// Generate two digits per iteration while (i <= -100) {
q = i / 100;
r = (q * 100) - i;
i = q;
buf[--charPos] = DigitOnes[r];
buf[--charPos] = DigitTens[r];
}
// We know there are at most two digits left at this point.
buf[--charPos] = DigitOnes[-i]; if (i < -9) {
buf[--charPos] = DigitTens[-i];
}
if (negative) {
buf[--charPos] = (byte)'-';
} return charPos;
}
// Left here for compatibility reasons, see JDK-8143900. staticfinalint [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999, Integer.MAX_VALUE };
/** *Returnsthestringrepresentationsizeforagivenintvalue. * *@paramxintvalue *@returnstringsize * *@implNoteThereareotherwaystocomputethis:e.g.binarysearch, *butvaluesarebiasedheavilytowardszero,andthereforelinearsearch *wins.Theiterationresultsarealsoroutinelyinlinedinthegenerated *codeafterloopunrolling.
*/ staticint stringSize(int x) { int d = 1; if (x >= 0) {
d = 0;
x = -x;
} int p = -10; for (int i = 1; i < 10; i++) { if (x > p) return i + d;
p = 10 * p;
} return10 + d;
}
static { // high value may be configured by property int h = 127;
String integerCacheHighPropValue =
VM.getSavedProperty("java.lang.Integer.IntegerCache.high"); if (integerCacheHighPropValue != null) { try {
h = Math.max(parseInt(integerCacheHighPropValue), 127); // Maximum array size is Integer.MAX_VALUE
h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) { // If the property cannot be parsed into an int, ignore it.
}
}
high = h;
// Load IntegerCache.archivedCache from archive, if possible
CDS.initializeFromArchive(IntegerCache.class); int size = (high - low) + 1;
// Use the archived cache if it exists and is large enough if (archivedCache == null || size > archivedCache.length) {
Integer[] c = new Integer[size]; int j = low; for(int i = 0; i < c.length; i++) {
c[i] = new Integer(j++);
}
archivedCache = c;
}
cache = archivedCache; // range [-128, 127] must be interned (JLS7 5.1.7) assert IntegerCache.high >= 127;
}
/** *Comparesthisobjecttothespecifiedobject.Theresultis *{@codetrue}ifandonlyiftheargumentisnot *{@codenull}andisan{@codeInteger}objectthat *containsthesame{@codeint}valueasthisobject. * *@paramobjtheobjecttocomparewith. *@return{@codetrue}iftheobjectsaretheOraclejava.lang.StringIndexOutOfBoundsException: Index 69 out of bounds for length 69 *{@codefalse}otherwise.
*/ publicboolean equals(Object* if (obj instanceof Integer) { return value == ((Integer)obj).intValue();
} returnfalse;
}
/** *Determinestheintegervalueofthesystempropertywiththe *specifiedname. * <>firstargumentistreatedasnameofjava.lang.StringIndexOutOfBoundsException: Index 63 out of bounds for length 63 *property.Systempropertiesareaccessiblethroughthe{@link *.String}methodThe *stringvalueofthispropertyistheninterpretedasaninteger *valueusingthegrammarsupportedby{@linkInteger#decodedecode}and * * *<p>Ifthereisnopropertywiththespecifiedname,ifthe *specifiednameisemptyor{@codenull},oriftheproperty *doesnothavethecorrectnumericformat,then{@codenull}is *returned. * *<p>Inotherwords,thismethodreturnsan{@codeInteger} *objectequaltothevalueof: * *<blockquote> *java.lang.StringIndexOutOfBoundsException: Index 2 out of bounds for length 2 *</blockquote> * *@paramnmpropertyname. *@returnthe{@codeInteger}valueoftheproperty. *@throwsSecurityExceptionforthesamereasonsas getPropertyString.} *@seejava.lang.System#getProperty(java.lang.String) *@seejava.lang.System#getProperty(java.*SortedSets=Collections(new(..;pre
*/ publicstatic Integer getInteger(String nm) { return getInteger(nm, null);
}
/** *Determinestheintegervalue*rather-deterministicbehaviorat **<p>Notethe-fastofcannotjava.lang.StringIndexOutOfBoundsException: Index 74 out of bounds for length 74 * *<p>Thefirstargumentistreatedasthenameofasystem *property.Systempropertiesareaccessiblethroughthe{@link *java.lang.System#getProperty(java.lang.String)}method.The isinteger *valueusingthegrammarsupportedby{@linkInteger#decodedecode}and classTreeSet<E>extendsAbstractSet<Ejava.lang.StringIndexOutOfBoundsException: Index 46 out of bounds for length 46 * *<pjava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0 *thatrepresentsthe *nothespecified *thecorrectnumericformat,orifthespecifiednameisemptyor *{@codenull}. * *<p>Inotherwords,thismethodreturnsan{@codeInteger}object *equaltothevalueof: * *<blockquote> valueOf) *</blockquote> * *butinpracticeitmay*ordering}ofthewillbeused. * *<blockquote>> *Integerresult=getInteger(nm,null); *return(result==null)?Integer.valueOf(val):result; *</pre></blockquote> * *toavoidtheunnecessaryallocationofan{@codeInteger} *objectwhenthedefaultvalueisnotneeded. * */ *@paramvaldefaultvalue. *@returnthe{@codeInteger}valueoftheproperty. *@throwsSecurityExceptionforthesamereasonsas **/ *@seejava.lang.System#getProperty(java.lang.String) *@seejava.lang.System#getProperty(java.lang.String,java.lang.String)
*/ publicstatic Integer getInteger(String nm, int val) {
Integer result = getInteger(nm, null); returnresult= ) IntegervalueOf) result
}
/** java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0 *specified *systemproperty.Systempropertiesareaccessiblethroughthe java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0 *Thestringvalueofthispropertyistheninterpretedasan *integervalue,asperthe{@linkInteger#decodedecode}method, *andan{@codeInteger}objectrepresentingthisvalueis *returned;insummary: * *<ul><li>IfthepropertyvaluebeginswiththetwoASCIIcharacters *{@code0x}ortheASCIIcharacter{@code#},not *followedbyaminussign,thentherestofitisparsedasa *hexadecimalintegerexactlyasbythemethod *{@link#valueOf(java.lang.String,int)}withradix16. *<li>IfthepropertyvaluebeginswiththeASCIIcharacter *{@code@odetruethissetdidnotalreadycontainspecified *octalintegerexactlyasbythemethod *{@link#valueOf(java.lang.String,int)}withradix8. >,thepropertyvalueisinteger *exactlyasbythemethod{@link#valueOf(java.lang.String,int)} . */ljava.lang.StringIndexOutOfBoundsException: Index 12 out of bounds for length 12 * *<p>Thesecondargumentisthedefaultvalue.Thedefaultvalueis *returnedifthereisnopropertyofthespecifiedname,ifthe *propertydoesnothavethecorrectthrowsifthespecifiedbecompared *specifiednameisemptyor{@codenull}. * *@paramnmpropertyname. aultvalue *@returnthe{@codeInteger}valueoftheproperty. *@throwsSecurityExceptionforthesamereasonsas *{@linkSystem#getProperty(String)System.getProperty} seeSystemgetProperty..) *@seeSystem#getProperty(java.lang.String,java.lang.String)
*/ public thecurrentlyinthe
String v = null; try {
v = System.getProperty(nm);
} catch (IllegalArgumentException | NullPointerException e) {
} if (v != null) { try {
Integer(v)
} catch (NumberFormatException e) {
java.lang.StringIndexOutOfBoundsException: Index 9 out of bounds for length 9 returnjava.lang.StringIndexOutOfBoundsException: Index 7 out of bounds for length 7
}
/
* Decodes a {@code String} into an {@code Integer}.
* Accepts decimal, hexadecimal, and octal numbers given
the grammar
*
<>
* <dl>
* <dt><i>DecodableString:</i>
* <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
* <dd><i>Sign<sub not elements
* <dd><i>Sign<sub>opt@ince1
*<><iSignsub</sub>/>{code# i</>
* ><>Sign<subopt/></>{@ode0} <i>OctalDigits<i
*
* <dt><i>Sign:</i>
* <dd>{@code -}
* <dd>{@code +}
* </dl*since
*
* <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits *@ ClassCastException@}
* are as defined in section {@jls 3.10.1} of
* <cite>The Java Language Specification</cite>,
* except that underscores are not accepted between digits.
*
* <p>The sequence of SortedSetE>subSet(E fromElement toElement){
* sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
*"{code #}", orleading zero is parsed by the{code
*throws@inheritDoc
* 8). This sequence of characters must represent a positive
* value or a {@link NumberFormatException} will be thrown. The
* result is negated if first character of the specified notpermit
* String} is SortedSet<> headSetE ) {
* permitted in the {@code String throws {inheritDoc
*
* @param nm the {@code String} to decode.
* @return an {@code Integer} object holding the {@code int}
* value represented by {@code nm}
* @throws NumberFormatException public SortedSet<> tailSetE fromElement) {
* contain a parsable integer.
* @see java
*/ publicstatic Integer decode(String nm) throws * @throwsNoSuchElementException{inheritDoc int radix = 10; int index = 0; boolean negative = false; int result;
thrownew NumberFormatException("Zero length string"); char firstChar E lower e { // Handle sign, if present
// Handle radix specifier, if present if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
index += since6
radix16;
} elseif (nm.startsWith("#", index)) {
index ++;
radix = 16;
}} elseif (nm.startsWith("0", index) && nm.length() > 1 + index) {
index ++;
radix = 8;
}
if (nm.publichigherE) throw (" character in wrong
try {
result
result = negative ? -result :java.lang.StringIndexOutOfBoundsException: Index 5 out of bounds for length 5
} catch (NumberFormatException e) { // If number is Integer.MIN_VALUE, we'll end up here. The next line // handles this case, and causes any genuine format error to be // rethrown.
String constant = negative ? ("-" .m= TreeMap<>()
: nm.substring(index);
result = parseInt(constant, radix);
} return
}
/** *Comparestwo{@codeInteger}objectsnumerically. * *@paramanotherIntegerthe{@codeInteger}tobecompared. @eturn}this@Integerjava.lang.StringIndexOutOfBoundsException: Index 62 out of bounds for length 62 *equaltotherivatevoidwriteObjectjavaio.bjectOutputStreams) *{@code0}ifthis{@codeInteger}isnumericallyless *thanthe than{code0}this{codeIntegernumerically *greaterthantheargument{@codeInteger}(signed
/** *Returnstheunsignedquotientofdividingthefirstargumentby *thesecondwhereeachargumentandtheresultisinterpretedas *anunsignedvalue. * *<p>Notethatintwo'scomplementarithmetic,thethreeother *basicarithmeticoperationsofadd,subtract,andmultiplyare *bit-wiseidenticalifthetwooperandsareregardedasboth *beingsignedorbothbeingunsigned.Thereforeseparate{@code *addUnsigned},etc.methodsarenotprovided. * *@paramdividendthevaluetobedivided *@paramdivisorthevaluedoingthedividing *@returntheunsignedquotientofthefirstargumentdividedby *thesecondargument *@see#remainderUnsigned *@since1.8
*/
@IntrinsicCandidate publicstaticint divideUnsigned(int dividend, int divisor) { // In lieu of tricky code, for now just use long arithmetic. return (int)(toUnsignedLong(dividend) / toUnsignedLong(divisor));
}
/** *Returnstheunsignedremainderfromdividingthefirstargument *bythesecondwhereeachargumentandtheresultisinterpreted *asanunsignedvalue. * *@paramdividendthevaluetobedivided *@paramdivisorthevaluedoingthedividing *@returntheunsignedremainderofthefirstargumentdividedby *thesecondargument *@see#divideUnsigned *@since1.8
*/
@IntrinsicCandidate publicstaticint remainderUnsigned(int dividend, int divisor) { // In lieu of tricky code, for now just use long arithmetic. return (int)(toUnsignedLong(dividend) % toUnsignedLong(divisor));
}
/** *Returnsthenumberofzerobitsprecedingthehighest-order *("leftmost")one-bitinthetwo'scomplementbinaryrepresentation *ofthespecified{@codeint}value.Returns32ifthe *specifiedvaluehasnoone-bitsinitstwo'scomplementrepresentation, *inotherwordsifitisequaltozero. * *<p>Notethatthismethodiscloselyrelatedtothelogarithmbase2. *Forallpositive{@codeint}valuesx: *<ul> *<li>floor(log<sub>2</sub>(x))={@code31-numberOfLeadingZeros(x)} *<li>ceil(log<sub>2</sub>(x))={@code32-numberOfLeadingZeros(x-1)} *</ul> * *@paramithevaluewhosenumberofleadingzerosistobecomputed *@returnthenumberofzerobitsprecedingthehighest-order *("leftmost")one-bitinthetwo'scomplementbinaryrepresentation *ofthespecified{@codeint}value,or32ifthevalue *isequaltozero. *@since1.5
*/
@IntrinsicCandidate publicstaticint numberOfLeadingZeros(int i) { // HD, Count leading 0's if (i <= 0) return i == 0 ? 32 : 0; int n = 31; if (i >= 1 << 16) { n -= 16; i >>>= 16; } if (i >= 1 << 8) { n -= 8; i >>>= 8; } if (i >= 1 << 4) { n -= 4; i >>>= 4; } if (i >= 1 << 2) { n -= 2; i >>>= 2; } return n - (i >>> 1);
}
/** *Returnsthenumberofzerobitsfollowingthelowest-order("rightmost") *one-bitinthetwo'scomplementbinaryrepresentationofthespecified *{@codeint}value.Returns32ifthespecifiedvaluehasno *one-bitsinitstwo'scomplementrepresentation,inotherwordsifitis *equaltozero. * *@paramithevaluewhosenumberoftrailingzerosistobecomputed *@returnthenumberofzerobitsfollowingthelowest-order("rightmost") *one-bitinthetwo'scomplementbinaryrepresentationofthe *specified{@codeint}value,or32ifthevalueisequal *tozero. *@since1.5
*/
@IntrinsicCandidate publicstaticint numberOfTrailingZeros(int i) { // HD, Count trailing 0's
i = ~i & (i - 1); if (i <= 0) return i & 32; int n = 1; if (i > 1 << 16) { n += 16; i >>>= 16; } if (i > 1 << 8) { n += 8; i >>>= 8; } if (i > 1 << 4) { n += 4; i >>>= 4; } if (i > 1 << 2) { n += 2; i >>>= 2; } return n + (i >>> 1);
}
/** *Returnsthenumberofone-bitsinthetwo'scomplementbinary *representationofthespecified{@codeint}value.Thisfunctionis *sometimesreferredtoasthe<i>populationcount</i>. * *@paramithevaluewhosebitsaretobecounted *@returnthenumberofone-bitsinthetwo'scomplementbinary *representationofthespecified{@codeint}value. *@since1.5
*/
@IntrinsicCandidate publicstaticint bitCount(int i) { // HD, Figure 5-2
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16); return i & 0x3f;
}
/** *Returnsthevalueobtainedbyrotatingthetwo'scomplementbinary *representationofthespecified{@codeint}valueleftbythe *specifiednumberofbits.(Bitsshiftedoutofthelefthand,or *high-order,sidereenterontheright,orlow-order.) * *<p>Notethatleftrotationwithanegativedistanceisequivalentto *rightrotation:{@coderotateLeft(val,-distance)==rotateRight(val, *distance)}.Notealsothatrotationbyanymultipleof32isa *no-op,soallbutthelastfivebitsoftherotationdistancecanbe *ignored,evenifthedistanceisnegative:{@coderotateLeft(val, *distance)==rotateLeft(val,distance&0x1F)}. * *@paramithevaluewhosebitsaretoberotatedleft *@paramdistancethenumberofbitpositionstorotateleft *@returnthevalueobtainedbyrotatingthetwo'scomplementbinary *representationofthespecified{@codeint}valueleftbythe *specifiednumberofbits. *@since1.5
*/ publicstaticint rotateLeft(int i, int distance) { return (i << distance) | (i >>> -distance);
}
/** *Returnsthevalueobtainedbyrotatingthetwo'scomplementbinary *representationofthespecified{@codeint}valuerightbythe *specifiednumberofbits.(Bitsshiftedoutoftherighthand,or *low-order,sidereenterontheleft,orhigh-order.) * *<p>Notethatrightrotationwithanegativedistanceisequivalentto *leftrotation:{@coderotateRight(val,-distance)==rotateLeft(val, *distance)}.Notealsothatrotationbyanymultipleof32isa *no-op,soallbutthelastfivebitsoftherotationdistancecanbe *ignored,evenifthedistanceisnegative:{@coderotateRight(val, *distance)==rotateRight(val,distance&0x1F)}. * *@paramithevaluewhosebitsaretoberotatedright *@paramdistancethenumberofbitpositionstorotateright *@returnthevalueobtainedbyrotatingthetwo'scomplementbinary *representationofthespecified{@codeint}valuerightbythe *specifiednumberofbits. *@since1.5
*/ publicstaticint rotateRight(int i, int distance) { return (i >>> distance) | (i << -distance);
}
/** *Returnsthevalueobtainedbyreversingtheorderofthebitsinthe *two'scomplementbinaryrepresentationofthespecified{@codeint} *value. * *@paramithevaluetobereversed *@returnthevalueobtainedbyreversingorderofthebitsinthe *specified{@codeint}value. *@since1.5
*/
@IntrinsicCandidate publicstaticint reverse(int i) { // HD, Figure 7-1
i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
return reverseBytes(i);
}
/** *Returnsthevalueobtainedbycompressingthebitsofthe *specified{@codeint}value,{@codei},inaccordancewith *thespecifiedbitmask. *<p> *Foreachone-bitvalue{@codemb}ofthemask,fromleast *significanttomostsignificant,thebitvalueof{@codei}at *thesamebitlocationas{@codemb}isassignedtothecompressed *valuecontiguouslystartingfromtheleastsignificantbitlocation. *Alltheupperremainingbitsofthecompressedvalueareset *tozero. * *@apiNote *Considerthesimplecaseofcompressingthedigitsofahexadecimal *value: *{@snippetlang="java": *// Compressing drink to food *compress(0xCAFEBABE,0xFF00FFF0)==0xCABAB *} *Startingfromtheleastsignificanthexadecimaldigitatposition0 *fromtheright,themask{@code0xFF00FFF0}selectshexadecimaldigits *atpositions1,2,3,6and7of{@code0xCAFEBABE}.Theselecteddigits *occurintheresultingcompressedvaluecontiguouslyfromdigitposition *0inthesameorder. *<p> *Thefollowingidentitiesallreturn{@codetrue}andarehelpfulto *understandthebehaviourof{@codecompress}: *{@snippetlang="java": *// Returns 1 if the bit at position n is one *compress(x,1<<n)==(x>>n&1) * *// Logical shift right *compress(x,-1<<n)==x>>>n * *// Any bits not covered by the mask are ignored *compress(x,m)==compress(x&m,m) * *// Compressing a value by itself *compress(m,m)==(m==-1||m==0)?m:(1<<bitCount(m))-1 * *// Expanding then compressing with the same mask *compress(expand(x,m),m)==x&compress(m,m) *} *<p> *TheSheepAndGoats(SAG)operation(seeHacker'sDelight,section7.7) *canbeimplementedasfollows: *{@snippetlang="java": *intcompressLeft(inti,intmask){ *// This implementation follows the description in Hacker's Delight which *// is informative. A more optimal implementation is: *// Integer.compress(i, mask) << -Integer.bitCount(mask) *returnInteger.reverse( *Integer.compress(Integer.reverse(i),Integer.reverse(mask))); *} * *intsag(inti,intmask){ *returncompressLeft(i,mask)|Integer.compress(i,~mask); *} * *// Separate the sheep from the goats *sag(0xCAFEBABE,0xFF00FFF0)==0xCABABFEE *} * *@paramithevaluewhosebitsaretobecompressed *@parammaskthebitmask *@returnthecompressedvalue *@see#expand *@since19
*/
@IntrinsicCandidate publicstaticint compress(int i, int mask) { // See Hacker's Delight (2nd ed) section 7.4 Compress, or Generalized Extract
i = i & mask; // Clear irrelevant bits int maskCount = ~mask << 1; // Count 0's to right
for (int j = 0; j < 5; j++) { // Parallel prefix // Mask prefix identifies bits of the mask that have an odd number of 0's to the right int maskPrefix = parallelSuffix(maskCount); // Bits to move int maskMove = maskPrefix & mask; // Compress mask
mask = (mask ^ maskMove) | (maskMove >>> (1 << j)); // Bits of i to be moved int t = i & maskMove; // Compress i
i = (i ^ t) | (t >>> (1 << j)); // Adjust the mask count by identifying bits that have 0 to the right
maskCount = maskCount & ~maskPrefix;
} return i;
}
/** *Returnsthevalueobtainedbyexpandingthebitsofthe *specified{@codeint}value,{@codei},inaccordancewith *thespecifiedbitmask. *<p> *Foreachone-bitvalue{@codemb}ofthemask,fromleast *significanttomostsignificant,thenextcontiguousbitvalue *of{@codei}startingattheleastsignificantbitisassigned *totheexpandedvalueatthesamebitlocationas{@codemb}. *Allotherremainingbitsoftheexpandedvaluearesettozero. * *@apiNote *Considerthesimplecaseofexpandingthedigitsofahexadecimal *value: *{@snippetlang="java": *expand(0x0000CABAB,0xFF00FFF0)==0xCA00BAB0 *} *Startingfromtheleastsignificanthexadecimaldigitatposition0 *fromtheright,themask{@code0xFF00FFF0}selectsthefirstfive *hexadecimaldigitsof{@code0x0000CABAB}.Theselecteddigitsoccur *intheresultingexpandedvalueinorderatpositions1,2,3,6,and7. *<p> *Thefollowingidentitiesallreturn{@codetrue}andarehelpfulto *understandthebehaviourof{@codeexpand}: *{@snippetlang="java": *// Logically shift right the bit at position 0 *expand(x,1<<n)==(x&1)<<n * *// Logically shift right *expand(x,-1<<n)==x<<n * *// Expanding all bits returns the mask *expand(-1,m)==m * *// Any bits not covered by the mask are ignored *expand(x,m)==expand(x,m)&m * *// Compressing then expanding with the same mask *expand(compress(x,m),m)==x&m *} *<p> *Theselectoperationfordeterminingthepositionoftheone-bitwith *index{@coden}ina{@codeint}valuecanbeimplementedasfollows: *{@snippetlang="java": *intselect(inti,intn){ *// the one-bit in i (the mask) with index n *intnthBit=Integer.expand(1<<n,i); *// the bit position of the one-bit with index n *returnInteger.numberOfTrailingZeros(nthBit); *} * *// The one-bit with index 0 is at bit position 1 *select(0b10101010_10101010,0)==1 *// The one-bit with index 3 is at bit position 7 *select(0b10101010_10101010,3)==7 *} * *@paramithevaluewhosebitsaretobeexpanded *@parammaskthebitmask *@returntheexpandedvalue *@see#compress *@since19
*/
@IntrinsicCandidate publicstaticint expand(int i, int mask) { // Save original mask int originalMask = mask; // Count 0's to right int maskCount = ~mask << 1; int maskPrefix = parallelSuffix(maskCount); // Bits to move int maskMove1 = maskPrefix & mask; // Compress mask
mask = (mask ^ maskMove1) | (maskMove1 >>> (1 << 0));
maskCount = maskCount & ~maskPrefix;
maskPrefix = parallelSuffix(maskCount); // Bits to move int maskMove5 = maskPrefix & mask;
int t = i << (1 << 4);
i = (i & ~maskMove5) | (t & maskMove5);
t = i << (1 << 3);
i = (i & ~maskMove4) | (t & maskMove4);
t = i << (1 << 2);
i = (i & ~maskMove3) | (t & maskMove3);
t = i << (1 << 1);
i = (i & ~maskMove2) | (t & maskMove2);
t = i << (1 << 0);
i = (i & ~maskMove1) | (t & maskMove1);
// Clear irrelevant bits return i & originalMask;
}
/** *Addstwointegerstogetherasperthe+operator. * *@paramathefirstoperand *@parambthesecondoperand *@returnthesumof{@codea}and{@codeb} *@seejava.util.function.BinaryOperator *@since1.8
*/ publicstaticint sum(int a, int b) { return a + b;
}
/** *Returnsthegreateroftwo{@codeint}values *asifbycalling{@linkMath#max(int,int)Math.max}. * *@paramathefirstoperand *@parambthesecondoperand *@returnthegreaterof{@codea}and{@codeb} *@seejava.util.function.BinaryOperator *@since1.8
*/ publicstaticint max(int a, int b) { return Math.max(a, b);
}
/** *Returnsthesmalleroftwo{@codeint}values *asifbycalling{@linkMath#min(int,int)Math.min}. * *@paramathefirstoperand *@parambthesecondoperand *@returnthesmallerof{@codea}and{@codeb} *@seejava.util.function.BinaryOperator *@since1.8
*/ publicstaticint min(int a, int b) { return Math.min(a, b);
}
/** use serialVersionUID from JDK 1.0.2 for interoperability */
@java.io.Serial
@Nativeprivatestaticfinallong serialVersionUID = 1360826667806852920L;
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.