我想优化数据库行应用程序设置。像这样的事情
10 - enabled option 1;
12 - enabled option 2;
13 - enabled option 3;
整个号码作为 1073741823 存储到数据库中。
我尝试实现这个:
公共(public)无效测试(){
// Let's say you get a String representing your option from your database
String optionFromDB= "132456";
// optionFromDB is a number like "132456"
// We transform it to bigDecimal:
BigDecimal myOptions=new BigDecimal(optionFromDB);
// Then we can use it.
// enable the option X (X is a number)
myOptions.setBit(2);
// Disable option X
myOptions.clearBit(2);
// Save the options to the db:
String newValToSave=myOptions.toString();
// do something if option x enable:
if (myOptions.testBit(123)){
System.out.println("test");
}
}
我怎样才能正确地实现这个?
最佳答案
假设 value 是一个整数 - 这将为您提供 32 个选项。如果这还不够,您可以使用 long(64 位)或将相同的逻辑应用于任意数量的位。
- 要启用位 n:值 |= 1 <<< n
- 要禁用位 n:值 &= ~(1 <<< n)
- 要测试位 n:(value & (1 <<< n)) != 0
- 转换为字符串:String s = Integer.toString(value)
- 从字符串转换: value = Integer.parseInt(s)
关于java - 将设置数组存储到数据库行中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51584286/