PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label int. Show all posts
Showing posts with label int. Show all posts

Sunday, October 30, 2022

[FIXED] How can I get input integers from user until he press enter by using eof?

 October 30, 2022     c, eof, input, int, scanf     No comments   

Issue

we start coding C and I cant solve my h.w because I dont know how to get input from the user (integers) until he press enter like 20 30 10 40 and after that the while done by using eof. here is part of the code that doesnt work,

printf("Students, please enter heights!\n");
   while((scanf("%d",&height))!=EOF)
    {
        if(height>0)
        {
            avg_girls=avg_girls+height;
            counter_girls++;
        }

        else
        {
            avg_boys=avg_boys+height;
            counter_boys++;
        }  
    }

I getting into infinity loop thanks you very much.


Solution

While a better way to accomplish reading an unknown number of integers from a line would be to read the entire line into a buffer of sufficient size and then step through the buffer using strtol (utilizing its endptr parameter to update your position in the buffer to 1-character past the last value converted), you can use scanf and accomplish the same thing.

One approach for using scanf to read multiple integers from a line of input is simply to read each character and confirm it is not the '\n' character or EOF. If the character isn't a digit (or a '-' sign preceding a digit - thanks Ajay Brahmakshatriya), then just go get the next character. If the character is a digit, put it back in stdin with ungetc and then call scanf and validate the conversion before updating either girls or boys average based on the sign of the input.

You could do something like the following:

    int height;

    fputs ("enter heights: ", stdout);

    while ((height = getchar()) != '\n' && height != EOF) {
        /* if not '-' and not digit, go read next char */
        if (height != '-' && !isdigit (height))
            continue;
        ungetc (height, stdin);     /* was digit, put it back in stdin */
        if (scanf ("%d", &height) == 1) {   /* now read with scanf */
            if (height > 0) {       /* postive val, add to girls */
                avg_girls += height;
                counter_girls++;
            }
            else {                  /* negative val, add to boys */
                avg_boys += height;
                counter_boys++;
            }
        }
    }

The isspace() macro is provided by the ctype.h header. If you cannot include other headers, then simply check whether height is a digit manually, e.g.

    if (height != '-' && (height < '0' || '9' < height))
        continue;

(remember you are reading characters with getchar(), so make the comparison against the ASCII characters for '0' and '9')

Another alternative is to read the entire line of input into a buffer and then repeatedly call sscanf converting integers as you work through the buffer additionally utilizing the "%n" specifier to report the number of characters consumed by the call to sscanf. (e.g. using "%d%n" and providing a pointer to int to hold the value provided by "%n") You can then keep a running total of the offset from the beginning of the buffer to add to your pointer to position sscanf for its next read.

Either way is fine, but reading a line-at-a-time presents many fewer pitfalls for the new C programmer to navigate than attempting to work with scanf and stdin itself.



Answered By - David C. Rankin
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, October 17, 2022

[FIXED] How do you read in a 3 byte size value as an integer in c++?

 October 17, 2022     byte, c++, id3, int     No comments   

Issue

I'm reading in an id3 tag where the size of each frame is specified in 3 bytes. How would I be able to utilize this value as an int?


Solution

Read each byte and then put them together into your int:

int id3 = byte0 + (byte1 << 8) + (byte2 << 16);

Make sure to take endianness into account.



Answered By - Carl Norum
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I store into a C++ variables using sqlite3?

 October 17, 2022     c++, database, int, sqlite     No comments   

Issue

I'm new in the world of C++.

I'm trying to store into a variable a value contained in a sqlite table that I've created but I don't know how to do (I research a lot befor asking here).

So, after I open the DB connection I execute this:

   char* sql = new char[4096];
   strcpy(sql, statement.c_str());

   /* Execute SQL statement */
   int rc = sqlite3_exec(DB, sql, callback, 0, &zErrMsg);

   if( rc != SQLITE_OK ){
      fprintf(stderr, "SQL ERROR: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   } else {
      fprintf(stdout, "STATEMENT:\n\n%s\n\nEXECUTED SUCCESSFULLY!\n\n", statement.c_str());
   }

And I get this:

OPENED DATABASE SUCCESSFULLY
sent = 0

sent = 0

sent = 0

sent = 0

sent = 0

sent = 1

sent = 1

sent = 1

STATEMENT:

SELECT sent FROM Message;

EXECUTED SUCCESSFULLY!

What I want to do is to store the value contained in "sent" (the datatype in the db is boolean) in a int variables that I can manipulate to check some condition. Or maybe to store all the values into a int array.

How can I do? Please help me!

Thanks a lot!

EDIT: I'm using sqlite3 library.

And this is my callback function:

static int callback(void *NotUsed, int argc, char **argv, char **azColName) {
   int i;
   for(i = 0; i<argc; i++) {
      printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
   }
   printf("\n");
   return 0;
}

Solution

Don't use sqlite3_exec() for anything that needs to do anything with the results of a query, or anything that involves user-supplied values. Use a prepared statement.

Something like

sqlite3_stmt *stmt;
int rc = sqlite3_prepare_v2(DB, statement.c_str(), statement.length(), &stmt, nullptr);
if (rc != SQLITE_OK) {
 // handle the error
}
// Loop through the results, a row at a time.
while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
 int sent = sqlite3_column_int(stmt, 0);
 // etc.
}
// Free the statement when done.
sqlite3_finalize(stmt);


Answered By - Shawn
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to properly instantiate os.FileMode

 October 17, 2022     file-permissions, go, int     No comments   

Issue

I have seen countless examples and tutorials that show how to create a file and all of them "cheat" by just setting the permission bits of the file. I would like to know / find out how to properly instantiate os.FileMode to provide to a writer during creation / updating of a file.

A crude example is this below:

func FileWrite(path string, r io.Reader, uid, gid int, perms string) (int64, error){
    w, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0664)
    if err != nil {
        if path == "" {
            w = os.Stdout
        } else {
            return 0, err
        }
    }
    defer w.Close()

    size, err := io.Copy(w, r)

    if err != nil {
        return 0, err
    }
    return size, err
}

In the basic function above permission bits 0664 is set and although this may make sense sometimes I prefer to have a proper way of setting the filemode correctly. As seen above a common example would be that the UID / GID is known and already provided as int values and the perms being octal digits that were previously gathered and inserted into a db as a string.


Solution

FileMode is just a uint32. http://golang.org/pkg/os/#FileMode

Setting via constants isn't "cheating", you use it like other numeric values. If you're not using a constant, you can use a conversion on valid numeric values:

mode := int(0777)
os.FileMode(mode)


Answered By - JimB
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I convert a Java HashSet<Integer> to a primitive int array?

 October 17, 2022     arrays, hashset, int, java     No comments   

Issue

I've got a HashSet<Integer> with a bunch of Integers in it. I want to turn it into an array, but calling

hashset.toArray();

returns an Object[]. Is there a better way to cast it to an array of int other than iterating through every element manually? I want to pass the array to

void doSomething(int[] arr)

which won't accept the Object[] array, even if I try casting it like

doSomething((int[]) hashSet.toArray());

Solution

Apache's ArrayUtils has this (it still iterates behind the scenes):

doSomething(ArrayUtils.toPrimitive(hashset.toArray()));

They're always a good place to check for things like this.



Answered By - Matthew Flaschen
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to print positive numbers with a prefix + in C++

 October 17, 2022     c++, int     No comments   

Issue

Is there any way to print the integer along with its sign in c++...i.e. by default if the number is negative we would get a - sign printed. In the same way can we get + before the positive numbers.

int x=-1;
cout<<"x="<<x;

gives output x=-1

but,..

int x=+1;
cout<<"x="<<x;

gives output as x=1 but how do i get it printed as x=+1

I know we can take cases by using if-else for x>0 and x<0;..but without using the if-else is there any direct way of printing in c++


Solution

Use std::showpos:

int x = 1;
std::cout << "x=" << std::showpos << x;


Answered By - NPE
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to make python print 1 as opposed to 1.0

 October 17, 2022     int, python     No comments   

Issue

I am making a math solving program, it keeps printing the whole numbers as decimals. Like 1 is 1.0, 5 is 5.0, and my code is:

print("Type in the cooridinates of the two points.")
    print("")
    print("---------------------")
    print("First point:")
    x1 = int(input("X: "))
    y1 = int(input("Y: "))
    print("")
    print("---------------------")
    print("Second point:")
    x2 = int(input("X: "))
    y2 = int(input("Y: "))
    m = (y1-y2) / (x1-x2)
    b = y1 - m * x1
    round(m, 0)
    round(b, 0)
    print("Completed equation:")
    print("")
    if b < 0:
        print("Y = "+ str(m) +"X - "+ str(b) +".")
    elif b > 0:
        print("Y = "+ str(m) +"X + "+ str(b) +".")
    elif b == 0:
        print("Y = "+ str(m) +"X.")
    input("Press enter to continue.")

Solution

Since you're dividing integers, Python represents the result as a float, not as an int. To format the floats as you'd like, you'll have to use string formatting:

>>> print('{:g}'.format(3.14))
3.14
>>> print('{:g}'.format(3.0))
3

So plugging it into your code:

print("Y = {:g}X - {}.".format(m, b))


Answered By - Blender
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to subtract two unsigned ints with wrap around or overflow

 October 17, 2022     c, int, overflow, subtraction     No comments   

Issue

There are two unsigned ints (x and y) that need to be subtracted. x is always larger than y. However, both x and y can wrap around; for example, if they were both bytes, after 0xff comes 0x00. The problem case is if x wraps around, while y does not. Now x appears to be smaller than y. Luckily, x will not wrap around twice (only once is guaranteed). Assuming bytes, x has wrapped and is now 0x2, whereas y has not and is 0xFE. The right answer of x - y is supposed to be 0x4.

Maybe,

( x > y) ? (x-y) : (x+0xff-y);

But I think there is another way, something involving 2s compliment?, and in this embedded system, x and y are the largest unsigned int types, so adding 0xff... is not possible

What is the best way to write the statement (target language is C)?


Solution

Assuming two unsigned integers:

  • If you know that one is supposed to be "larger" than the other, just subtract. It will work provided you haven't wrapped around more than once (obviously, if you have, you won't be able to tell).
  • If you don't know that one is larger than the other, subtract and cast the result to a signed int of the same width. It will work provided the difference between the two is in the range of the signed int (if not, you won't be able to tell).

To clarify: the scenario described by the original poster seems to be confusing people, but is typical of monotonically increasing fixed-width counters, such as hardware tick counters, or sequence numbers in protocols. The counter goes (e.g. for 8 bits) 0xfc, 0xfd, 0xfe, 0xff, 0x00, 0x01, 0x02, 0x03 etc., and you know that of the two values x and y that you have, x comes later. If x==0x02 and y==0xfe, the calculation x-y (as an 8-bit result) will give the correct answer of 4, assuming that subtraction of two n-bit values wraps modulo 2n - which C99 guarantees for subtraction of unsigned values. (Note: the C standard does not guarantee this behaviour for subtraction of signed values.)



Answered By - Matthew Slattery
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why is it bad to use short

 October 17, 2022     c, c++, int, types, variables     No comments   

Issue

It is very common that even in script where the developer have guarantees that the variable will never exceed one byte and sometimes two bytes; Many people decide to use int types for every possible variable used to represent numbers nay in the range of 0-1.

Why does it hurt so much to use char or short instead?

I think I heard someone saying int is "more standard" type of.. type. What does this mean. My question is does the data type int have any defined advantages over short (or other lesser data types), because of which advantages, people used to almost always resort to int?


Solution

As a general rule, most arithmetic in C is performed using type int (that is, plain int, not short or long). This is because (a) the definition of C says so, which is related to the fact that (b) that's the way many processors (at least, the ones C's designers had in mind) prefer to work.

So if you try to "save space" by using short ints instead, and you write something like

short a = 1, b = 2;
short c = a + b;

the compiler may have to emit code to, in effect, convert a from short to int, convert b from short to int, do the addition, and convert the sum back to short. You may have saved a little bit of space on the storage for a, b, and c, but your code may end up being bigger (and slower).

If you instead write

int a = 1, b = 2;
int c = a + b;

you might spend a little more storage space on a, b, and c, but the code might be smaller and quicker.

This is somewhat of an oversimplified argument, but it's behind your observation that usage of type short is rare, and plain int is generally recommended. Basically, since it's the machine's "natural" size, it's presumed to be the most straightforward type to do arithmetic in, without extra conversions to and from less-natural types. It's sort of a "When in Rome, do as the Romans do" argument, but it generally does make using plain int advantageous.

If you have lots of not-so-large integers to store, on the other hand (a large array of them, or a large array of structures containing not-so-large integers), the storage savings for the data might be large, and worth it as traded off against the (relatively smaller) increase in the code size, and the potential speed increase.

See also this previous SO question and this C FAQ list entry.


Addendum: like any optimization problem, if you really care about data space usage, code space usage, and code speed, you'll want to perform careful measurements using your exact machine and processor. Your processor might not end up requiring any "extra conversion instructions" to convert to/from the smaller types, after all, so using them might not be so much of a disadvantage. But at the same time you can probably confirm that, for isolated variables, using them might not yield any measurable advantage, either.


Addendum 2. Here's a data point. I experimented with the code

extern short a, b, c;

void f()
{
    c = a + b;
}

I compiled with two compilers, gcc and clang (compiling for an Intel processor on a Mac). I then changed short to int and compiled again. The int-using code was 7 bytes smaller under gcc, and 10 bytes smaller under clang. Inspection of the assembly language output suggests that the difference was in truncating the result so as to store it in c; fetching short as opposed to int doesn't seem to change the instruction count.

However, I then tried calling the two different versions, and discovered that it made virtually no difference in the run time, even after 10000000000 calls. So the "using short might make the code bigger" part of the answer is confirmed, but maybe not "and also make it slower".



Answered By - Steve Summit
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to send integer array over udp socket in C?

 October 17, 2022     arrays, c, int, sockets     No comments   

Issue

I have to send an int array over an udp socket. Do I have to convert it as char array or as a sequence of byte? What is the standard solution?


Solution

You could just do as follow:

int array[100];
sendto(sockfd, array, sizeof(array), 0, &addr, addrlen);

To recv your array the other side (assuming you always send array of the same size):

int array[100];
recvfrom(sockfd, array, sizeof(array), 0, &addr, &addrlen);

As said in the comments, you have to be carefull about the architecture of the system which send / receive the packet. If you're developping an application for 'standard' computers, you should not have any problem, if you want to be sure:

  • Use a fixed-size type (include stdint.h and use int32_t or whatever is necessary for you.
  • Check for endianess in your code.

Endianess conversion:

// SENDER   

int32_t array[100] = ...;
int32_t arrayToSend[100];
for (int i = 0; i < 100; ++i) {
    arrayToSend[i] = htonl(array[i]);
}
sendto(sockfd, arrayToSend, sizeof(arrayToSend), 0, &addr, addrlen);

// RECEIVER

int32_t array[100];
int32_t arrayReceived[100];
recvfrom(sockfd, arrayReceived, sizeof(arrayReceived), 0, &addr, &addrlen);
for (int i = 0; i < 100; ++i) {
    array[i] = ntohl(arrayReceived[i]);
}


Answered By - Holt
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to convert single quotes string to number in python

 October 17, 2022     int, python, single-quotes, string     No comments   

Issue

I have a number of type string with single quotes. e,g

var = '2,000'
type(var) # <class 'str'>

I want to convert it to int.

I have tried int(var) But it gives an error

invalid literal for int() with base 10: '2,000'


Solution

If your number contains ',' then you should use this.

 > var = '2,000'
 > int(a.replace(',', ''))
 > 2000

else this

 >  var = '2000'
 >  i = int(var)


Answered By - Sanjit Prasad
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to convert an Int to a Character in Swift

 October 17, 2022     character, int, ios, swift, var     No comments   

Issue

I've struggled and failed for over ten minutes here and I give in. I need to convert an Int to a Character in Swift and cannot solve it.

Question

How do you convert (cast) an Int (integer) to a Character (char) in Swift?

Illustrative Problem/Task Challenge

Generate a for loop which prints the letters 'A' through 'Z', e.g. something like this:

    for(var i:Int=0;i<26;i++) {      //Important to note - I know 
        print(Character('A' + i));   //this is horrendous syntax...
    }                                //just trying to illustrate! :)

Solution

You can't convert an integer directly to a Character instance, but you can go from integer to UnicodeScalar to Character and back again:

let startingValue = Int(("A" as UnicodeScalar).value) // 65
for i in 0 ..< 26 {
    print(Character(UnicodeScalar(i + startingValue)))
}


Answered By - Nate Cook
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to convert string values to integer values while reading a CSV file?

 October 17, 2022     csv, int, loops, python, string     No comments   

Issue

When opening a CSV file, the column of integers is being converted to a string value ('1', '23', etc.). What's the best way to loop through to convert these back to integers?

import csv

with open('C:/Python27/testweight.csv', 'rb') as f:
    reader = csv.reader(f)
    rows = [row for row in reader if row[1] > 's']

for row in rows:
    print row

CSV file below:

Account Value
ABC      6
DEF      3
GHI      4
JKL      7

Solution

I think this does what you want:

import csv

with open('C:/Python27/testweight.csv', 'r', newline='') as f:
    reader = csv.reader(f, delimiter='\t')
    header = next(reader)
    rows = [header] + [[row[0], int(row[1])] for row in reader if row]

for row in rows:
    print(row)

Output:

['Account', 'Value']
['ABC', 6]
['DEF', 3]
['GHI', 4]
['JKL', 7]


Answered By - martineau
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, August 11, 2022

[FIXED] Why output of int 070 is 56 in C program?

 August 11, 2022     c, decimal, int, octal     No comments   

Issue

Can you explain it? Why it given 56 value as output?

#include <stdio.h> 
#include <conio.h>

void main()
{
    int x = 070;
    printf("%d", x);
    getch();
}

Solution

Any integer literal (integer constant) starting with 0 is an octal representation.

Quoting C11, chapter §6.4.4.1, Integer constants

octal-constant:

 0
 octal-constant octal-digit

and

octal-digit: one of

  0 1 2 3 4 5 6 7

and, as per chapter §7.21.6.1, for %d format specifier with printf(), (emphasis mine)

d,i The int argument is converted to signed decimal [...]

Thereby, octal 70 == decimal 56.



Answered By - Sourav Ghosh
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is the point of writing integer in hexadecimal, octal and binary?

 August 11, 2022     decimal, floating-point, int, swift, var     No comments   

Issue

I am well aware that one is able to assign a value to an array or constant in Swift and have those value represented in different formats.

For Integer: One can declare in the formats of decimal, binary, octal or hexadecimal.

For Float or Double: One can declare in the formats of either decimal or hexadecimal and able to make use of the exponent too.

For instance:

var decInt = 17
var binInt = 0b10001
var octInt = 0o21
var hexInt = 0x11

All of the above variables gives the same result which is 17.

But what's the catch? Why bother using those other than decimal?


Solution

There are some notations that can be way easier to understand for people even if the result in the end is the same. You can for example think in cases like colour notation (hexadecimal) or file permission notation (octal).



Answered By - CarlosMorente
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, August 10, 2022

[FIXED] Why can't I unbox an int as a decimal?

 August 10, 2022     c#, decimal, int, unboxing     No comments   

Issue

I have an IDataRecord reader that I'm retrieving a decimal from as follows:

decimal d = (decimal)reader[0];

For some reason this throws an invalid cast exception saying that the "Specified cast is not valid."

When I do reader[0].GetType() it tells me that it is an Int32. As far as I know, this shouldn't be a problem....

I've tested this out by this snippet which works just fine.

int i = 3750;
decimal d = (decimal)i;

This has left me scratching my head wondering why it is failing to unbox the int contained in the reader as a decimal.

Does anyone know why this might be occurring? Is there something subtle I'm missing?


Solution

You can only unbox a value type to its original type (and the nullable version of that type).

By the way, this is valid (just a shorthand for your two line version):

object i = 4;
decimal d = (decimal)(int)i; // works even w/o decimal as it's a widening conversion

For the reason behind this read this Eric Lippert's blog entry: Representation and Identity

Personally, I categorize things done by cast syntax into four different types of operation (they all have different IL instructions):

  1. Boxing (box IL instruction) and unboxing (unbox IL instruction)
  2. Casting through the inhertiance hierarchy (like dynamic_cast<Type> in C++, uses castclass IL instruction to verify)
  3. Casting between primitive types (like static_cast<Type> in C++, there are plenty of IL instructions for different types of casts between primitive types)
  4. Calling user defined conversion operators (at the IL level they are just method calls to the appropriate op_XXX method).


Answered By - mmx
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, July 21, 2022

[FIXED] How to convert an int value to string in Go?

 July 21, 2022     converters, go, int, string     No comments   

Issue

i := 123
s := string(i) 

s is 'E', but what I want is "123"

Please tell me how can I get "123".

And in Java, I can do in this way:

String s = "ab" + "c"  // s is "abc"

how can I concat two strings in Go?


Solution

Use the strconv package's Itoa function.

For example:

package main

import (
    "strconv"
    "fmt"
)

func main() {
    t := strconv.Itoa(123)
    fmt.Println(t)
}

You can concat strings simply by +'ing them, or by using the Join function of the strings package.



Answered By - Klaus Byskov Pedersen
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to Convert Int to Unsigned Byte and Back

 July 21, 2022     byte, int, java     No comments   

Issue

I need to convert a number into an unsigned byte. The number is always less than or equal to 255, and so it will fit in one byte.

I also need to convert that byte back into that number. How would I do that in Java? I've tried several ways and none work. Here's what I'm trying to do now:

int size = 5;
// Convert size int to binary
String sizeStr = Integer.toString(size);
byte binaryByte = Byte.valueOf(sizeStr);

and now to convert that byte back into the number:

Byte test = new Byte(binaryByte);
int msgSize = test.intValue();

Clearly, this does not work. For some reason, it always converts the number into 65. Any suggestions?


Solution

A byte is always signed in Java. You may get its unsigned value by binary-anding it with 0xFF, though:

int i = 234;
byte b = (byte) i;
System.out.println(b); // -22
int i2 = b & 0xFF;
System.out.println(i2); // 234


Answered By - JB Nizet
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to check if an integer includes a certain number in c#

 July 21, 2022     c#, int, integer, numbers     No comments   

Issue

Is there a way I can check Integers if they contain a certain number in C#?

For example:

I want to check for 7. When I enter 17, the code will return 1. When I enter 28, the code will return 0.

Thank You


Solution

int number = 17;
int digit = 7;
bool result = number.ToString().Contains(digit.ToString());


Answered By - Jakub Lortz
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to convert an Int to a String of a given length with leading zeros to align?

 July 21, 2022     formatting, int, scala, string     No comments   

Issue

How can I convert an Int to a 7-character long String, so that 123 is turned into "0000123"?


Solution

The Java library has pretty good (as in excellent) number formatting support which is accessible from StringOps enriched String class:

scala> "%07d".format(123)
res5: String = 0000123

scala> "%07d".formatLocal(java.util.Locale.US, 123)
res6: String = 0000123

Edit post Scala 2.10: as suggested by fommil, from 2.10 on, there is also a formatting string interpolator (does not support localisation):

val expr = 123
f"$expr%07d"
f"${expr}%07d"

Edit Apr 2019:

  • If you want leading spaces, and not zero, just leave out the 0 from the format specifier. In the above case, it'd be f"$expr%7d".Tested in 2.12.8 REPL. No need to do the string replacement as suggested in a comment, or even put an explicit space in front of 7 as suggested in another comment.
  • If the length is variable, s"%${len}d".format("123")


Answered By - huynhjl
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing