Java boolean to bit

Java Convert boolean to byte

In this Java core tutorial we learn how to convert a boolean value into byte value in Java programming language.

How to convert boolean to byte in Java

To convert an boolean value to byte we simply map the boolean true value to 1 in byte and false value to 0 in byte.

byte byteValue = (byte)(booleanValue ? 1 : 0);

The following Java example code we convert a boolean true value to byte.

public class BooleanToByteExample1  public static void main(String. args)  boolean booleanValue = true; byte byteValue = (byte)(booleanValue ? 1 : 0); System.out.println("Boolean value: " + booleanValue); System.out.println("Byte value: " + byteValue); > >
Boolean value: true Byte value: 1

In the following Java example code we convert a boolean false value to byte.

public class BooleanToByteExample2  public static void main(String. args)  boolean booleanValue = false; byte byteValue = (byte)(booleanValue ? 1 : 0); System.out.println("Boolean value: " + booleanValue); System.out.println("Byte value: " + byteValue); > >
Boolean value: false Byte value: 0

Источник

Converting boolean data type to bit in Java

The question is, can I convert boolean data type into bit data type in Java then use the converted value to store it into the table? Edit: Notice that Java hasn’t any bit data type, but boolean is represented in memory with 1 bit Solution 2: Java offers a class that allows to compact multiple boolean values but it should be used when there are relatively large to replace.

Converting boolean data type to bit in Java

I’ve been working recently on «How to import excel files into database’s tables». In this case, I have a column with bit data type. Meanwhile in Java I have a variable with boolean data type. The question is, can I convert boolean data type into bit data type in Java then use the converted value to store it into the table? Here’s the script i’ve been working on recently

boolean isDiscount = (boolean) nextCell.getBooleanCellValue(); statement.setBoolean(8, isDiscount); 

As said @Turing85 java hasn’t any bit datatype.

Anyway, if I got well your goal, with bit data type in excel col, you mean 0-1 (0= false, 1= true). I suppose you mean that. (?)

Altought Java not use «bit data type», you could convert a boolean into a integer value [0, 1] and then write it in excel’s cell

 private int funcName(boolean flag) < return flag ? 1 : 0; >//Now write the integer returned into spreadsheet 

Hope this is useful for your achieve 🙂

Edit: Notice that Java hasn’t any bit data type, but boolean is represented in memory with 1 bit

Java offers a BitSet class that allows to compact multiple boolean values but it should be used when there are relatively large boolean[] to replace.

BitSet statement = new BitSet(16); // represent 16 bits boolean isDiscount = (boolean) nextCell.getBooleanCellValue(); statement.set(8, isDiscount); 

However, storing BitSet in the database (e.g. via BLOB ) may get too complicated in comparison to mapping Java boolean to BIT type in SQL.

Casting — Convert boolean to int in Java, Boolean#compareTo is the way to go in those specific cases. Java 7 introduced a new utility function that works with primitive types directly, Boolean#compare (Thanks shmosel) int boolToInt (boolean b) < return Boolean.compare (b, false); >Will be inlined by modern JIT’s, so not necessarily inefficient. Usage exampleint myInt = myBoolean ? 1 : 0;Feedback

Utility method to convert Boolean into boolean and handle null in Java

Is there a utility method in Java which converts Boolean into boolean and automatically handles null reference to Boolean as false?

boolean x = Boolean.TRUE.equals(value); 

? That’s a single expression, which will only evaluate to true if value is non-null and a true-representing Boolean reference.

static boolean getPrimitive(Boolean value)
static boolean getPrimitive(Boolean value)

Are you looking for a ready-made utility ? Then I think Commons-Lang BooleanUtils is the answer. It has a method toBoolean(Boolean bool).

If you’re golfing, an explicit null check followed by automatic unboxing is shorter than the canonical answer.

boolean b=o!=null&&o; // For golfing purposes only, don't use in production code 

Converting Boolean to Integer in Java without If, bool = True num = 1 * ( bool ) I also figure you could do. boolean bool = True; int myint = Boolean.valueOf ( bool ).compareTo ( false ); This …

Java Android Gson convert boolean to int from response server

Help me, guys! Please, advise a simple solution to convert type boolean from server to int in Android 🙂 When I log in, i get respone from server like this :

,"response":>,"access_token":"15629e234e04a54a5a44ef2aa4eccb1d">> 

Then I get undefined exception: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected NUMBER but was BOOLEAN

This happens because of JsonElement » allow_dev » is boolean from server, and in Android I have » allow_dev » like int .

 private void login(String email, String pass) < showProgress(); JsonObject params = new JsonObject(); params.addProperty("username", email); params.addProperty("password", pass); UserOperationsTask task = new UserOperationsTask(UserOperationsTask.TaskMode.MODE_LOGIN, params) < @Override public void onLoadFinished(Bundle res) < hideProgress(); String errorMessage = res.getString(UserOperationsTask.RESULT_ERROR_STRING); if (errorMessage != null) < showMessage(getString(R.string.login_error), getString(R.string.server_request_error)); >else < String json = res.getString(UserOperationsTask.RESULT_JSON_STRING); if (json != null) < JsonParser parser = new JsonParser(); JsonObject responseData = parser.parse(json).getAsJsonObject(); JsonObject companyObj = responseData.getAsJsonObject("profile").getAsJsonObject("company"); >setRegisteredMode(); > > >; task.execute(this); > 

This method parse response and I tried to convert allow_dev type from boolean to int, but I dont understand whether I’m doing right?

private Bundle parseProfileResponse(Context context, JsonObject responseData) < Log.d(TAG, "parseProfileResponse"); // I tried convert allow_dev type from boolean to int String allow_dev_server = String.valueOf(responseData.get("allow_dev")); boolean b = allow_dev_server.equals("true"); int allow_dev = b ? 1 : 0; // true == 1 Profile profile; profile = GsonHolder.getGSONInstance().fromJson(responseData.getAsJsonObject("profile"), Profile.class); profile.allow_dev = allow_dev; Bundle res = new Bundle(); res.putParcelable(RESULT_OBJ, profile); res.putString(RESULT_JSON_STRING, responseData.toString()); try < Cache.saveToCache(context, profile); >catch (RemoteException e) < Log.d(TAG, "parseAuthResponse RemoteException: " + e.toString()); res.putString(RESULT_ERROR_STRING, context.getString(R.string.database_error)); >catch (OperationApplicationException e) < Log.d(TAG, "parseAuthResponse OperationApplicationException: " + e.toString()); res.putString(RESULT_ERROR_STRING, context.getString(R.string.database_error)); >return res; > 

I have to get » allow_dev » convert it in int and write to database.

If you can switch to mappings, you can use everything static typing can give you, comparing to weakly «typed» JsonElement and its subclasses. It has several advantages: compile-time checking, more robust code, IDE support, etc. The major disadvantage is that you have to write custom mappings, however you there tools (online as well) that can try to generate simple mapping classes based on the given sample JSON (for example, a very popular tool here: http://www.jsonschema2pojo.org/).

Now, let’s create some mappings. The mappings like the ones below are used rarely: final fields (used for «server responses» that are no supposed to be modified programmatically; Gson can assign such fields anyway); null for non-primitives and some hacks for primitive type defaults values to cheat the compiler (like Integer.value(0) but not simply 0 : otherwise, javac may inline constants, thus Gson cannot affect them); no getters/setters (data-transfer objects are just data bags, but yes, getters can work better). Anyway, you can use your style, and the followings mappings are used for demonstration purposes (the mappings code has even compact formatting: one property per line collapsing the annotations).

final class Response  < final Status status = null; final T response = null; >final class Status < final int error = Integer.valueOf(0); final int code = Integer.valueOf(0); final String message = null; >final class ProfileAndAccessToken < final Profile profile = null; @SerializedName("access_token") final String accessToken = null; >final class Profile < final int final String username = null; @SerializedName("full_name") final String fullName = null; final String phone = null; final int verified = Integer.valueOf(0); final int admin = Integer.valueOf(0); @SerializedName("allow_dev") @JsonAdapter(BooleanToIntTypeAdapter.class) final int allowDev = Integer.valueOf(0); final Company company = null; >final class Company

Note two annotations above:

  • @SerializedName — this annotation can «rename» fields so you can use even special characters (however it’s discouraged, and it’s typically used to map incoming JSON property names to javaCamelNamingConventions).
  • @JsonAdapter — this annotation can «attach» a special type adapter to a certain field, so that it could convert JSON properties to the given field and vice versa.

Now let’s implement a type adapter that can convert incoming boolean values to local int values and vice versa. Note that type adapters work in streaming manner, so you have to read JSON tokens stream on fly during read, and, of course, generate JSON tokens stream during write.

final class BooleanToIntTypeAdapter extends TypeAdapter  < // Public constructors may be evil, and let expose as less as possible // Gson can still instantiate this type adapter itself private BooleanToIntTypeAdapter() < >@Override @SuppressWarnings("resource") public void write(final JsonWriter out, final Integer value) throws IOException < // If the given value is null, we must write the `null` token to the output JSON tokens stream anyway in order not to break JSON documents if ( value == null ) < out.nullValue(); return; >// Let's assume that we can accept either 0 or 1 that are mapped to false and true respectively switch ( value ) < case 0: out.value(false); break; case 1: out.value(true); break; default: // Or throw an exception as fast as we can throw new IllegalArgumentException("Cannot convert " + value + " to a boolean literal"); >> @Override public Integer read(final JsonReader in) throws IOException < // Peek the next token type, and if it's null, then return null value too if ( in.peek() == NULL ) < return null; >// Otherwise parse the next token as boolean and map it either to 1 or 0 return in.nextBoolean() ? 1 : 0; > > 

That’s all you need in Gson. Now, for you entire JSON, since the response mapping class is generic, you have to tell Gson what the T is. Gson accepts java.lang.reflect.Type in the fromJson method, and this type can hold both raw and parameterized types, so Gson could (de)serialize more accurately.

private static final Type profileAndAccessTokenResponse = new TypeToken>() < >.getType(); final Response response = gson.fromJson(JSON, profileAndAccessTokenResponse); System.out.println(response.response.profile.allowDev); System.out.println(gson.toJson(response, profileAndAccessTokenResponse)); 

Note that the first line is 0 : this what is generated with BooleanToIntTypeAdapter . Backing to your code:

String allow_dev_server = String.valueOf(responseData.get("allow_dev")); boolean b = allow_dev_server.equals("true"); int allow_dev = b ? 1 : 0; // true == 1 Profile profile; profile = GsonHolder.getGSONInstance().fromJson(responseData.getAsJsonObject("profile"), Profile.class); profile.allow_dev = allow_dev; 

Can be replaced with simple:

final Profile profile = GsonHolder.getGSONInstance().fromJson(responseData.getAsJsonObject("profile"), Profile.class) // now `Profile.allowDev` is 0 or 1 automatically 

Note that responseData can be replace with a particular mapping, so you could even not parse at that line: probably you might simply pass the whole response object as a class mapping rather that JsonObject in your parseProfileResponse — it would be more robust.

Convert boolean to int in Java, The Boolean class object has functions such as compareTo that we can use: public static int booleanObjectMethodToInt(Boolean foo) < return …

Источник

Java Utililty Methods Boolean to Byte

Method

if (value == true) < return 1; return 0;
if (x) < return new byte[] < (byte) 1 >; > else < return new byte[] < (byte) 0 >;
byte val = 0; for (boolean b : array) < val if (b) val |= 1; return val;
byte[] byt = new byte[bool.length]; for (int i = 0; i < bool.length; i += 1) < byt[i] = bool[i] ? (byte) 'T' : (byte) 'F'; return byt;
if (values == null) < return null; byte[] results = new byte[values.length]; for (int i = 0; i < values.length; i++) < results[i] = (byte) (values[i] == true ? 1 : 0); return results; .
if (flags.length > 8) throw new IllegalArgumentException("You cannot store more than 8 bits on a byte!"); byte n = 0; for (int i = 0; i < flags.length; i++) < if (flags[i]) n += (1 return n; .
return new byte[] < (byte) (b ? 1 : 0) >;
byte[] buffer = new byte[1]; booleanToBytes(b, buffer); return buffer;

Источник

Читайте также:  Javascript имя вызвавшей функции
Оцените статью