英文:
Controlling the maximum value of an unsigned int
问题
如果我有一个4位的无符号整数,最大值为15。如果值为0,然后减去1,得到的是15。我可以将位大小增加1,使最大值变为31,依此类推。这很不错,但我希能够控制最大值为2^n - 1以外的值。
我要如何创建一种自定义类型,以便在实例化时可以控制这个最大值,同时保持与无符号整数相同的效率?
我考虑的用例是,我希望能够像使用循环链表一样处理元素数组,而不使用链表。如果这个问题很愚蠢,请原谅!
英文:
If I have a 4-bit unsigned integer, the maximum value is 15. If the value is 0 and I subtract 1, I get 15. I can increase the bit size by 1 and have the maximum value be 31, and so on and so forth. This is great, but I want to be able to control the maximum value to be values other than 2^n - 1.
How do I create a custom type such that I can control this maximum value when I instantiate it while maintaining the same efficiency as an unsigned int?
The use case for this I am thinking of is so that I can treat an array of elements like a circularly linked list without using a linked list. Sorry if this is a stupid question!
答案1
得分: 1
你可以使用取模运算符%
,它返回两个操作数之间的余数。例如,如果您想要最大值为13,假设您使用变量i
进行索引,您可以执行array[i % 14]
,这将导致索引仅在范围0 -> 13内。我不确定是否有办法创建具有此属性的自定义类型,除非您创建一个类并实现加法和减法运算符的方法,以创建与无符号整数相同的行为。以下是要点:
public class MaxInt {
private final int max;
private int value;
public MaxInt(int max, int value) {
this.max = max;
this.value = value;
}
public MaxInt plus(int a) {
return new MaxInt(this.max, (this.value + a) % (this.max + 1));
}
public MaxInt minus(int a) {
return new MaxInt(this.max, (this.value - a) % (this.max + 1));
}
public int getValue() {
return this.value;
}
}
然后您可以使用new MaxInt(13, 0)
进行类似操作,您的值将在0 -> 13之间。
英文:
You can use the modulus operator %
which returns the remainder between two operands. For example, if you wanted the maximum value to be 13, assuming you're indexing with a variable i
, you can do array[i % 14]
which will result in the index only being in the range 0 -> 13. I'm not sure if there is a way to create a custom type with this property, unless you created a class and implemented the methods for the add and subtract operators to create the same behavior as with your unsigned integer. Here's the gist of it:
public class MaxInt {
private final int max;
private int value;
public MaxInt(int max, int value) {
this.max = max;
this.value = value;
}
public MaxInt plus(int a) {
return new MaxInt(this.max, (this.value + a) % (this.max + 1));
}
public MaxInt minus(int a) {
return new MaxInt(this.max, (this.value - a) % (this.max + 1));
}
public getValue() {
return this.value;
}
}
Then you could do the same with new MaxInt(13, 0)
and your value will be between 0 -> 13.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论