• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

caffeware

Banned
I'm working on a low resorts system and I need to set bits individually in C.

So I have an unsigned short, and I need to manipulate ONLY the first 8 bits using a second number.

Code:
unsigned short n1 = 0; //[X][X][X][X][X][X][X][X][0][0][0][0][0][0][0][0]
unsigned char  n2 = 4; //[0][0][0][0][0][1][0][0]
// I have to set the "1 0 0" in n1 without touching the X values.

Right now I'm switching all first 8 bits "off" and the doing "n1 = n1 | n2" ?

What's the best way of doing this? Thank you.
 

CTLance

Member
I'm working on a low resorts system and I need to set bits individually in C.

So I have an unsigned short, and I need to manipulate ONLY the first 8 bits using a second number.

Right now I'm switch of all first 8 bits "off" and the doing "n1 = n1 | n2" ?

What's the best way of doing this? Thank you.
Ooooh, bitwise logic. Always fun.

Warning: You say "1 0 0", that's three bits. I am assuming you only want to set those and not the full lower byte or nibble.

Here's the slow and step-by-step version.

Clear the three bits in n1:
n1 = n1 & 0xFFF8;
(preparation for step 3 due to using OR to get the bits into n1)
(use 0xFFF0 if 4 bits, 0xFF00 if 8 bits)

Prepare n2, clearing all unimportant bits:
n2 = n2 & 0x0007;
(we do not wish to alter anything but the bits we want)
(use 0x000F if 4 bits, 0x00FF if 8 bits)

Set the three bits:
n1 = n1 | n2;

I might be a bit rusty at this, but it should work. You can also use shifts to clear the bits, which might be faster - depending on your target architecture, of course.

Also, please be advised that unsigned shorts can be anything between 16 and 64 Bits wide. This might very well complicate things depending on how portable you want your code to be.

Shorter version.

Also helpful because readability is king:
#define bit_get(p,m) ((p) & (m))
#define bit_set(p,m) ((p) |= (m))
#define bit_clear(p,m) ((p) &= ~(m))
#define bit_flip(p,m) ((p) ^= (m))
#define bit_write(c,p,m) (c ? bit_set(p,m) : bit_clear(p,m))
#define BIT(x) (0x01 << (x))
#define LONGBIT(x) ((unsigned long)0x00000001 << (x))
 

Minamu

Member
Are there any good places to learn more about the underlying code that gets generated when you make a program with Windows Form (C# version)? I recently made an event based calculator but I also need to explain how all the classes fit together and cooperate :( And I have no clue what all these things do xD
 

Godslay

Banned
Are there any good places to learn more about the underlying code that gets generated when you make a program with Windows Form (C# version)? I recently made an event based calculator but I also need to explain how all the classes fit together and cooperate :( And I have no clue what all these things do xD

Hopefully I am understanding what you are asking.

For general information on C# as a language, the new boston (http://thenewboston.org/list.php?cat=15) is decent for understanding C# a bit better.

If you are specifically asking about a certain portion of code, click on the portion of code and hit F12. F12 allows you to go to the definition of a portion of code. This allows you to see the underlying details of what you program.

If you want to go deeper you can use ildasm.exe to view the MSIL code. Here's a tutorial:
http://msdn.microsoft.com/en-us/library/aa309387(v=vs.71).aspx. It's using the old Framework 1.1, but I'm assuming it will still work fine if you need to go that deep.

Good luck!
 

Minamu

Member
Hopefully I am understanding what you are asking.

For general information on C# as a language, the new boston (http://thenewboston.org/list.php?cat=15) is decent for understanding C# a bit better.

If you are specifically asking about a certain portion of code, click on the portion of code and hit F12. F12 allows you to go to the definition of a portion of code. This allows you to see the underlying details of what you program.

If you want to go deeper you can use ildasm.exe to view the MSIL code. Here's a tutorial:
http://msdn.microsoft.com/en-us/library/aa309387(v=vs.71).aspx. It's using the old Framework 1.1, but I'm assuming it will still work fine if you need to go that deep.

Good luck!
Thanks, I think the newboston and F12 will suffice. Hopefully, reading up on the eventHandler and such is enough.
 

nan0

Member
Are there any good places to learn more about the underlying code that gets generated when you make a program with Windows Form (C# version)? I recently made an event based calculator but I also need to explain how all the classes fit together and cooperate :( And I have no clue what all these things do xD

The designer only generates the code in the *.Designer.cs file, which is mainly a bunch of attributes for all your controls, as well as the initialization of the event handlers. There isn't really that much to explain about, there is a reason that it gets put in a partial class (you usually doesn't need to touch it, since it can get overwritten any time).

D.Rosen from Wolfire (Lugaru, Overgrowth) has written an interesting blog post covering this topic (link), worth reading.

I would take it with a grain of salt though, since the author seems somewhat opposed to proprietary software and Microsoft in general. Saying that OpenGL is more powerful than DX an then putting some Utah Teapot Wireframe rendering right below that is a bit naive. Also the claim that 50% of gamers still use XP is invalid now (since the article is 3 years old).
 
Similar to what Kalnos says, I think the best idea would be to use an interface (this looks like Java), collect the methods that the different types share and put them there, then have the classes you want to put in the arraylist implement that interface.

I am still not far into java so we haven't been introduced to interfaces yet.

Kind of lost on what to do for this assignment. Any guidance would be great. Thank you.
 

nan0

Member
I am still not far into java so we haven't been introduced to interfaces yet.

Kind of lost on what to do for this assignment. Any guidance would be great. Thank you.

What exactly is your assignment? Just parsing the textfile? You could write a class for each shape with attributes such as isFilled, fillColor, width, height etc. and create an object for each line of text. Then set the attributes of that object accordingly. If you write some getters and setters you can easily alter or retreive the value of each attribute. Just make sure that if an attribute isn't set (e.g. has no color) to set and return some meaningful values, to prevent exceptions/crashes.
 
What exactly is your assignment? Just parsing the textfile? You could write a class for each shape with attributes such as isFilled, fillColor, width, height etc. and create an object for each line of text. Then set the attributes of that object accordingly. If you write some getters and setters you can easily alter or retreive the value of each attribute.

Thanks for the quick response. Yes my assignment is checking a text file that has the type of shape (rectangle or circle and it's attributes). I already created classes for each one and it's getters and setters but having a hard time how to place these attributes into an arraylist and then adding the total area.
 
I would take it with a grain of salt though, since the author seems somewhat opposed to proprietary software and Microsoft in general. Saying that OpenGL is more powerful than DX an then putting some Utah Teapot Wireframe rendering right below that is a bit naive. Also the claim that 50% of gamers still use XP is invalid now (since the article is 3 years old).

Eh, faster draw calls is still true. Almost every OpenGL renderer for emulators is faster. Almost all of my own game projects ran faster if I used an OpenGL pipeline. It's also nice because you get easy detection and access to vendor extensions.

The only advantage of DX is it's a hell of lot simpler to use.
 

nan0

Member
Thanks for the quick response. Yes my assignment is checking a text file that has the type of shape (rectangle or circle and it's attributes). I already created classes for each one and it's getters and setters but having a hard time how to place these attributes into an arraylist and then adding the total area.

You don't need to place the attributes into an Arraylist, but the objects. If you don't have a superclass "Shape" or similar, create an Arraylist for each type of shape, iterate over the list and add up the area. Than add up the area of all lists.

Something like this:
Code:
//Create lists
ArrayList<Rectangle> Rectangles= new ArrayList<Rectangle>();
ArrayList<Circle> Circles= new ArrayList<Circle>();

//Add new object to list
Rectangles.Add(new Rectangle(color, isFilled, width, height));

//Iterate over list
int rectangleArea = 0;
for (Rectangle rec : Rectangles){
        rectangleArea  += rec.getArea();
}

//Add up everything
int fullArea = rectangleArea + circleArea;
System.out.println("Overall area is "+ fullArea);
 

Godslay

Banned
Got an interview for a backend jr java dev position at AT&T tomorrow.

What kind of technical questions can I expect?

I'm having a hard time digging anything up specifically on AT&T interview questions. Did you ask if they are going to have to you code/answer technical questions or if it's a behavioral interview?

If it's just technical questions, then I would brush up with something like this:

http://www.techinterviews.com/master-list-of-java-interview-questions

It's a little old, you might be able to find something newer. Most of it is relevant though.

If it's coding then go over your data structures and algorithms.

If it's behavioral, then be yourself and do a mock interview as prep.

Usually I can dig up some stuff on Glassdoor.com as far as interview questions, but couldn't find anything for AT&T.
 
You don't need to place the attributes into an Arraylist, but the objects. If you don't have a superclass "Shape" or similar, create an Arraylist for each type of shape, iterate over the list and add up the area. Than add up the area of all lists.

Something like this:
Code:
//Create lists
ArrayList<Rectangle> Rectangles= new ArrayList<Rectangle>();
ArrayList<Circle> Circles= new ArrayList<Circle>();

//Add new object to list
Rectangles.Add(new Rectangle(color, isFilled, width, height));

//Iterate over list
int rectangleArea = 0;
for (Rectangle rec : Rectangles){
        rectangleArea  += rec.getArea();
}

//Add up everything
int fullArea = rectangleArea + circleArea;
System.out.println("Overall area is "+ fullArea);

I do have a superclass called GeometricObjects. I appreciate your input.
 

nan0

Member
I do have a superclass called GeometricObjects. I appreciate your input.

I'm not sure if that works in Java, but then you can just have one generic list of GeometricObjects and call getArea() on all list items (provided all subclasses have implemented getArea()).

Code:
//Create list
ArrayList<GeometricObjects> MyObjects= new ArrayList<GeometricObjects>();

//Add new object to list
MyObjects.Add(new Rectangle(color, isFilled, width, height));
MyObjects.Add(new Circle(color, isFilled, radius));

//Iterate over list
int area= 0;
for (GeometricObjects obj: MyObjects){
        area  += obj.getArea();
}
 

usea

Member
Thanks, I think the newboston and F12 will suffice. Hopefully, reading up on the eventHandler and such is enough.
If you haven't figured it out already, start by looking in Program.cs. That'll be the main entry point when your program is run. It probably just makes a new Form1 and then shows it or something. Then you can look at the code for Form1 (either hit F12 when your cursor is on it or find it in solution explorer). Look at the constructor first, then any other code that gets called. From there you should be able to find all the code.

Thanks for the quick response. Yes my assignment is checking a text file that has the type of shape (rectangle or circle and it's attributes). I already created classes for each one and it's getters and setters but having a hard time how to place these attributes into an arraylist and then adding the total area.
I remember your question before, but I was never very clear what you're trying to do and what you're having problems with? Is there any way you can provide more details on what part is stumping you?

If I recall you have a text file to parse, where each line defines a shape and you have to calculate the area of the shape defined by the line of text. What does an arraylist have to do with where you're stuck?
 
I remember your question before, but I was never very clear what you're trying to do and what you're having problems with? Is there any way you can provide more details on what part is stumping you?

If I recall you have a text file to parse, where each line defines a shape and you have to calculate the area of the shape defined by the line of text. What does an arraylist have to do with where you're stuck?

I am just confused on a lot of subject when it comes to coding. Kinda feeling over-whelmed to be quite honest. I will just post the homework assignment so you may get a clear understanding of what I am trying to do here:

This problem is based on the GeometricObject class introduced in chapter 13.
Write a Java program to create an ArrayList holding Circle and Rectangle objects. The program will
traverse the list adding the area of all objects in the collection. At the end, the program prints the grand
total. Test your program with the sample disk data shown below.
Hints:
1. Define an ArrayList<GeometricObject> object, call it list.
2. Define the abstract class GeometricObject and its subclasses Circle and Rectangle as
indicated in chapter 13 (already discussed in class).
3. For each row in the input file
a. Create a new Circle or Rectangle object.
b. Add the new object to the list.
4. Traverse the list adding each object’s area to an accumulator
5. Print the total area
Observation
Each line begins consists of several strings. The first string indicates the object’s type (Circle or
Rectangle). In the case of a circle the next token represents either its radius (in case it is numeric) or the
object’s color, followed by its ‘filled’ attribute and finally its radius. Similar strategy is used for Rectangle
objects.
 

Minamu

Member
The designer only generates the code in the *.Designer.cs file, which is mainly a bunch of attributes for all your controls, as well as the initialization of the event handlers. There isn't really that much to explain about, there is a reason that it gets put in a partial class (you usually doesn't need to touch it, since it can get overwritten any time).
It's for a course so I probably need to explain it all no matter how trivial :)

If you haven't figured it out already, start by looking in Program.cs. That'll be the main entry point when your program is run. It probably just makes a new Form1 and then shows it or something. Then you can look at the code for Form1 (either hit F12 when your cursor is on it or find it in solution explorer). Look at the constructor first, then any other code that gets called. From there you should be able to find all the code.
Thanks, sounds like a smart move. I probably need to read up on the background theory in the course litterature too though.
 

usea

Member
I am just confused on a lot of subject when it comes to coding. Kinda feeling over-whelmed to be quite honest. I will just post the homework assignment so you may get a clear understanding of what I am trying to do here:
Sorry about you feeling overwhelmed. It is very common, which sucks.

A good approach for solving a problem is breaking it down into smaller steps and solving each one of those. Fortunately you already have a pretty good road map with those hints. It looks like you're stuck on step 3 in that list. I'll post an example of how you might solve step 3, step-by-step so you can see the process. Sorry if it's long. I just want to show everything so you get how one might do this problem.

Here's what you said earlier for some examples of the shape definition lines:
Code:
Circle 1
Circle red true 1
Rectangle 10 20
Rectangle blue true 1 5
This is actually a little tricky since parts of the definition are optional.

Break the problem down into smaller steps. I see from your code before you already know how to read the text from a file into a string. That's a good step. What we really want is each line of the file in its own string. That solves the problem of finding where one shape definition ends and another starts, since one line in the file is one shape. It seems Scanner has hasNextLine() and nextLine() methods for this.
Code:
Scanner s = new Scanner(new File("mydata.txt"));
ArrayList<String> shapeLines = new ArrayList<String>();
while (s.hasNextLine()){
	shapeLines.add(s.nextLine());
}
s.close();
After the above code, shapeLines is an ArrayList where each entry in the list is a shape definition string. But it's still just a big string, so the next step could be converting one big string into a shape.

We can break down that step into smaller steps. A first step of "converting one big string into a shape" could be to split the string into words, so that we have a string for each part of the shape definition. e.g. "Circle", "red", "true", "1" instead of the whole things "Circle red true one".

You should be able to use string split for that. It takes a string and divides it into smaller strings. We want to divide on spaces, so we pass it a space. (It actually operates on regular expressions, which gets complicated. but for this case we can just give it a space). Also the line from the file contains the invisible carriage return at the end of the line, so we'll use .trim() to remove that.
Code:
for(String shapeLine : shapeLines) { //we want to do this for all the lines of text we read from the file
	String[] shapeWords = shapeLine.trim().split(" "); //we split the line by spaces, so now this has each individual word from the line shapeLine.
	//we'll use the words here, since they only exist for this iteration of the loop
}

Now, we know the first word is always the type of shape (Circle or Rectangle). And we know that for Circles the last number is the radius (or diameter, not sure), and for Rectangles the last 2 numbers are width and height. The part we don't know, is whether there is a color and/or a filled (true/false) in the words.

Recall that our goal at this point is to convert some words into a shape. We can use the first word to determine the type of shape, and go from there.
Code:
for(String shapeLine : shapeLines) {
	String[] shapeWords = shapeLine.split(" ");
	if(shapeWords.length > 0) { //just in case one of the lines from the file was blank, we only want to convert it into a shape if there are actually any words in the array
		String shapeType = shapeWords[0]; //the first word, which should be Rectangle or Circle
		if(shapeType == "Rectangle") {
			//make a rectangle here, using the other words
		}
		else if(shapeType == "Circle") {
			//make a circle here, using the other words
		}
	}
}

So now we need to use the other words in shapeWords to determine the color (if any), whether or not it's filled, and the size. In the input data you pasted, shape definitions seem to have either a color and filled, or neither. If we want to make the assumption that that is always true, we can count the number of words to determine how to process it. Let's start by doing that.
Code:
for(String shapeLine : shapeLines) {
	String[] shapeWords = shapeLine.split(" ");
	if(shapeWords.length > 0) {
		String shapeType = shapeWords[0];
		if(shapeType == "Rectangle") {
			if(shapeWords.length == 3) { //"Rectangle" "10" "20" is 3 words, so this is the case where there is no color or filled
				int width = Integer.parseInt(shapeWords[1]);
				int height = Integer.parseInt(shapeWords[2]);
				//make the rectangle here
			}
			else if(shapeWords.length == 5) { //"Rectangle" "blue" "true" "1" "5" is 5 words, so this is the case where there is everything
				String color = shapeWords[1];
				boolean filled = Boolean.parseBoolean(shapeWords[2]);
				int width = Integer.parseInt(shapeWords[3]);
				int height = Integer.parseInt(shapeWords[4]);
				//make the rectangle here
			}
		}
		else if(shapeType == "Circle") {
			if(shapeWords.length == 2) { //"Circle" "1" is 2 words, so this is the case where there is no color or filled
				int radius = Integer.parseInt(shapeWords[1]);
				//make the circle here
			}
			else if(shapeWords.length == 4) { //"Circle" "red" "true" "1" is 4 words
				String color = shapeWords[1];
				boolean filled = Boolean.parseBoolean(shapeWords[2]);
				int radius = Integer.parseInt(shapeWords[3]);
				//make the circle here
			}
		}
	}
}
This will work, but if you come across a circle that has 3 words or a rectangle that has 4 words, it will skip it. You don't have any of these in the data you pasted, but if they do exist then you will need to add another "else if" clause on shapeWords of those lengths that determine whether the 2nd word is a color or true/false. Here is how that would look for the rectangle. It works by checking if the 2nd word is "true" or "false". In either case, it represents whether or not the shape is filled. If it's neither true nor false, it must be a color.
Code:
else if (shapeWords.length == 4) {
	String secondWord = shapeWords[1].toLowerCase();
	boolean filled = false;
	String color = "";
	if(secondWord == "true" || secondWord == "false") {
		filled = Boolean.parseBoolean(secondWord);
	}
	else {
		color = secondWord;
	}
	//make the rectangle here, dealing with the possibility of color being an empty string.
}
Now you just have to make your Circle or Rectangle object, at the location in the code of those comments about making them. How you do this depends on how you defined the constructor in your classes, but you have all the parts to make them.

After that, you need to make an ArrayList of GeometricObject and add your rectangle/circle to it. Example:
Code:
ArrayList<GeometricObject> shapes = new ArrayList<GeometricObject>();
for(String shapeLine : shapeLines) {
	String[] shapeWords = shapeLine.split(" ");
	if(shapeWords.length > 0) {
		String shapeType = shapeWords[0];
		if(shapeType == "Rectangle") {
			if(shapeWords.length == 3) {
				int width = Integer.parseInt(shapeWords[1]);
				int height = Integer.parseInt(shapeWords[2]);
				Rectangle rect = new Rectangle(width, height);
				shapes.add(rect);
			}
			else if(shapeWords.length == 5) {
				String color = shapeWords[1];
				boolean filled = Boolean.parseBoolean(shapeWords[2]);
				int width = Integer.parseInt(shapeWords[3]);
				int height = Integer.parseInt(shapeWords[4]);
				Rectangle rect = new Rectangle(color, filled, width, height);
				shapes.add(rect);
			}
		}
		else if(shapeType == "Circle") {
			if(shapeWords.length == 2) {
				int radius = Integer.parseInt(shapeWords[1]);
				Circle circle = new Circle(radius);
				shapes.add(circle);
			}
			else if(shapeWords.length == 4) {
				String color = shapeWords[1];
				boolean filled = Boolean.parseBoolean(shapeWords[2]);
				int radius = Integer.parseInt(shapeWords[3]);
				Circle circle = new Circle(color, filled, radius);
				shapes.add(circle);
			}
		}
	}
}
Note that the constructors for Circle and Rectangle in that code are just examples. Now you can follow the next steps, of going over your list of shapes and calculating the area, etc.

One thing that might trip you up is if your text file has multiple spaces in-a-row, like
Code:
Circle blue   1
In this case, string split would give you something like "Circle" "blue" " " " " "1" which would cause everything else to not work correctly. If this is a concern, change shapeLine.split(" ") into shapeLine.split("\\s+"). The second one means "one or more spaces." so it will divide on one or more spaces instead of always one. This probably won't be an issue though.

You'll notice that the code is fairly long. We repeated a lot of stuff that you can reduce by reorganizing it. And there's never just one way of doing something, this is just one way you might go about converting a text that defines a shape into shape objects.

For completion's sake, here's how I broke the problem down (which is absolutely not the only way you could do it). It makes things seem a lot simpler if you break them down into steps like this.
Code:
- Make shape objects from a text file
  |- Read lines from the file
    |- Use Scanner and nextLine
  |- Make a shape from each line
    |- Break each line down into words
    |- Use the words to make a shape
      |- Use the first word to determine the shape
      |- Convert the rest of the words into properties of the shape
        |- Use the number of words to determine which words correspond to which properties of the shape
        |- Use integer.parseInt and Boolean.parseBoolean to convert some of the properties

Also I haven't used java since I was in school, and I typed this in notepad without testing it. So it could definitely have some errors.
 

caffeware

Banned
Thanks for everything, specially for those sexy functions. :)

I have a question about this:

Clear the three bits in n1:
n1 = n1 & 0xFFF8;
(use 0xFFF0 if 4 bits, 0xFF00 if 8 bits)

Prepare n2, clearing all unimportant bits:
n2 = n2 & 0x0007;
(use 0x000F if 4 bits, 0x00FF if 8 bits)

How do you come with a number like"0xFFF0" ? Is there a formula?

Thank you!
 
Thanks for everything, specially for those sexy functions. :)

I have a question about this:



How do you come with a number like"0xFFF0" ? Is there a formula?

Thank you!
Well, it comes from thinking using bitwise logic, and applying it to get a number useful for whatever you need to do. First, the properties of AND, OR, and XOR:

x AND 1 = x
x AND 0 = 0

x OR 1 = 1
x OR 0 = x

x XOR 1 = ~x (1 if x is 0, 0 if x is 1)
x XOR 0 = x

Using these properties, you'd build up a number by figuring which bits need to be changed in what way, and applying those changes using a certain number, determined by the operation used. For example, say you need to reset the least significant 4 bits of a number (set them to 0). You'd note that:

1. Bits need to be reset (set to 0), so the AND operation should be used
2. In the number you AND with the original, the bits in the positions that you need to reset should be 0 (because of the above property of the AND operation), and the rest should be 1.

So, following from that, since it's a 16-bit number, the number you need to use to reset the least significant 4 bits of a given number is:

1111 1111 1111 0000

or, in hex:

0xFFF0

You'd do a similar process if you need to set bits (OR), or flip bits(AND). Hex is useful here, since it's less obvious looking at the number 65528 what it's supposed to do.
 
I'm having a hard time digging anything up specifically on AT&T interview questions. Did you ask if they are going to have to you code/answer technical questions or if it's a behavioral interview?

If it's just technical questions, then I would brush up with something like this:

http://www.techinterviews.com/master...view-questions

It's a little old, you might be able to find something newer. Most of it is relevant though.

If it's coding then go over your data structures and algorithms.

If it's behavioral, then be yourself and do a mock interview as prep.

Usually I can dig up some stuff on Glassdoor.com as far as interview questions, but couldn't find anything for AT&T.

That link is quite useful, bookmarked thanks!

Speaking of interviews, how 'important' is technical questions for entry level positions? I always tend to fumble on those :(

Not really good at textbook questions.
 

CTLance

Member
ColtraineGF caffeware, Hex to Bin and back is rather easy once you "get it".

At first it boggles the mind, but with a little practice you'll be doing this subconsciously in no time at all.

So, let's say we have 101001011001 and want to get the corresponding Hex number.

So, first, let's cut them up into groups of four.

101001011001 -> 1010 0101 1001

Each group of four bits corresponds to one hex number. Convenient.

Now, let's get those values.

Code:
          (MSB)                       (LSB)
BIT    |    7   6   5   4   3   2   1   0
       +---------------------------------
VALUE  |  128  64  32  16   8   4   2   1

Value of Bit = 2 ^ (Position of Bit in Byte from the right beginning with 0)

With four bits we only have four bit values: 8,4,2,1. So, let's look at the first group of bits.

1010 -> 1*8 + 0*4 + 1*2 + 0*1 = 10

Easy, right? You just add the values together whenever a bit is set.

Code:
DEC   || 15 14 13 12 11 10  9  8  7  6  5  4  3  2  1  0 
======++================================================
HEX   ||  F  E  D  C  B  A  9  8  7  6  5  4  3  2  1  0

Use this table to convert the 10 into correct hex notation. "A" is what we're looking for.

Now, do this again for the other two groups and we end up with A 5 9.

Now just slam a 0x in front of that, so that C knows you're talking Hex and you're done.

101001011001 = 0xA59
 
That link is quite useful, bookmarked thanks!

Speaking of interviews, how 'important' is technical questions for entry level positions? I always tend to fumble on those :(

Not really good at textbook questions.

A must. Any company worth their salt will use technical questions to select the better candidates. Start reviewing your data structures and algorithms.
 
Anyone know why when I keep getting zombie (read defunct) process when I fork child processes? I tell the parent to wait while the child runs and exits, but the child is still always listed when I use the 'ps' command.

I'm working on a 'shell' (couple basic commands) and ideally all of the defunct processes shouldn't show up when I execute the command from within my shell.
 

CTLance

Member
Yeppers, I was hasty, I meant to address caffeware. Double D'Oh. Ah well, in my defense, it was late at night. Still, argh...
 
Anyone know why when I keep getting zombie (read defunct) process when I fork child processes? I tell the parent to wait while the child runs and exits, but the child is still always listed when I use the 'ps' command.

I'm working on a 'shell' (couple basic commands) and ideally all of the defunct processes shouldn't show up when I execute the command from within my shell.

Are you actually waiting or using WNOHANG?

I used multiprocessing to make a proxy for my networking class and it was forking 20 or more processes per web page at times which obviously resulted in zombie central so I had to figure out the whole wait thing. I don't know the structure of your program, but with mine I would be waiting until a request comes in from a browser and just after I forked, I would call my zombie process cleanup. I used the following function to do it. I hope it helps. It's not the best code. For example, I'm not even using status, so technically I could just pass in null, but the project was rushed and that slipped. Also, it does skip an element when an element is removed at the moment. I just saw that. Derp derp.

Code:
void zombieProcessCleanup( std::vector<pid_t>& vChildProcs )
{
    int status;
	
    for( std::vector<int>::iterator iter = vChildProcs.begin(); iter < vChildProcs.end(); ++iter )
    {
        int testpid = waitpid( *iter, &status, WNOHANG );
		
	// confirms process status has changed, so remove from vector as process will not be in process table anymore
	if( testpid == *iter )
	    iter = vChildProcs.erase( iter );
    }
}
 
Are you actually waiting or using WNOHANG?

I used multiprocessing to make a proxy for my networking class and it was forking 20 or more processes per web page at times which obviously resulted in zombie central so I had to figure out the whole wait thing. I don't know the structure of your program, but with mine I would be waiting until a request comes in from a browser and just after I forked, I would call my zombie process cleanup. I used the following function to do it. I hope it helps. It's not the best code. For example, I'm not even using status, so technically I could just pass in null, but the project was rushed and that slipped. Also, it does skip an element when an element is removed at the moment. I just saw that. Derp derp.

Was just using wait. Upon further inspection that would lead me to believe that that is my issue. guh. I'll have to look into that. Can't use std::vector since it's gotta be all C tho.

Anyway another simple one: I need to split an argument into multiple tokens, and for the most part I'm successful. Problem is, any proper input must be formatted with an extra space when entering it.

Code:
fgets(arg, 10, stdin);
arg1 = strtok_r(arg, " ", &arg);
arg2 = strtok_r(arg, " ", &arg);
arg3 = strtok_r(arg, " ", &arg);

So when I want it to process a command, say ls, I have to explicitly type "ls_" because plain ol "ls" won't work. I'm know it has to do with how I'm delimiting it, since I'm assuming strtok_r includes the delimited character (in my case) as the end part of the string...
 
Was just using wait. Upon further inspection that would lead me to believe that that is my issue. guh. I'll have to look into that. Can't use std::vector since it's gotta be all C tho.

Anyway another simple one: I need to split an argument into multiple tokens, and for the most part I'm successful. Problem is, any proper input must be formatted with an extra space when entering it.

Code:
fgets(arg, 10, stdin);
arg1 = strtok_r(arg, " ", &arg);
arg2 = strtok_r(arg, " ", &arg);
arg3 = strtok_r(arg, " ", &arg);

So when I want it to process a command, say ls, I have to explicitly type "ls_" because plain ol "ls" won't work. I'm know it has to do with how I'm delimiting it, since I'm assuming strtok_r includes the delimited character (in my case) as the end part of the string...

From the linux man pages on strtok_r:

char *strtok_r(char *str, const char *delim, char **saveptr);

The strtok_r() function is a reentrant version strtok(). The saveptr argument is a pointer to a char * variable that is used internally by strtok_r() in order to maintain context between successive calls that parse the same string.

On the first call to strtok_r(), str should point to the string to be parsed, and the value of saveptr is ignored. In subsequent calls, str should be NULL, and saveptr should be unchanged since the previous call.

So you're using strtok_r wrong basically.

Go here to read more.

Learning to use these manpages will save you a LOT in the future so get used to them.
 

Thank you so much. I really appreciate your time and effort into helping. I did put some work into my assignment yesterday. Also, my classes for circle and rectangle have a zero argument constructor and a three argument constructor.

How would I implement this into the driver?

I know how to create an object ala Circle c1 = new Circle();, but I have no idea what else to do. Sorry if I ask to many questions. Just sort of lost here.

Thanks again.
 

usea

Member
Thank you so much. I really appreciate your time and effort into helping. I did put some work into my assignment yesterday. Also, my classes for circle and rectangle have a zero argument constructor and a three argument constructor.

How would I implement this into the driver?

I know how to create an object ala Circle c1 = new Circle();, but I have no idea what else to do. Sorry if I ask to many questions. Just sort of lost here.

Thanks again.
No problem.

I assume your Rectangle and Circle classes have a string for color and a boolean for filled. I assume your zero-argument constructor sets those to some default value?

Use the zero-argument constructor and just set the properties afterwards. Like
Code:
Rectangle rect = new Rectangle();
rect.width = width;
rect.height = height;
//and if you have these values (only in some cases):
rect.color = color;
rect.filled = filled;

And something similar for Circle (omitting the height obviously) You can use the non-empty constructor if you happen to have the 3 values it takes, but I don't know what those are.
 

Mordeccai

Member
Hi programming GAF,

I'm currently taking an introductory class in Python to be used in bioinformatics. But I also have a goal to make my first android app by the end of the year. I have no idea what kind of app I want to make but its just a little goal I've set for myself. What other languages should I start learning on the side to prepare for this? I'm working off the assumption that once I finish this semester of python being taught from an instructor picking up other languages from Google won't be as much of a challenge.
 
Hi programming GAF,

I'm currently taking an introductory class in Python to be used in bioinformatics. But I also have a goal to make my first android app by the end of the year. I have no idea what kind of app I want to make but its just a little goal I've set for myself. What other languages should I start learning on the side to prepare for this? I'm working off the assumption that once I finish this semester of python being taught from an instructor picking up other languages from Google won't be as much of a challenge.
C++ or Java or both?
 
Hi programming GAF,

I'm currently taking an introductory class in Python to be used in bioinformatics. But I also have a goal to make my first android app by the end of the year. I have no idea what kind of app I want to make but its just a little goal I've set for myself. What other languages should I start learning on the side to prepare for this? I'm working off the assumption that once I finish this semester of python being taught from an instructor picking up other languages from Google won't be as much of a challenge.

Why not use Python?

http://code.google.com/p/android-scripting/
http://kivy.org/
https://github.com/kivy/python-for-android
 
I need help with a program. I need to Write a function that takes one numeric parameter as students grade and returns letter grade value for that grade. These are the grades i need to do it with:

>93 "A"
90-93 "A-"
87 - 93 "B+"
84 - 87 "B"
80 - 84 "B-"
75 - 80 "C+"
70 - 75 "C"
<70 "F"
 

usea

Member
I need help with a program. I need to Write a function that takes one numeric parameter as students grade and returns letter grade value for that grade. These are the grades i need to do it with:

>93 "A"
90-93 "A-"
87 - 93 "B+"
84 - 87 "B"
80 - 84 "B-"
75 - 80 "C+"
70 - 75 "C"
<70 "F"
Do you have any more details? Like, do you have to do it in a particular language? Do you have to take the input values from any particular location? What part do you need help with?
 
Do you have any more details? Like, do you have to do it in a particular language? Do you have to take the input values from any particular location? What part do you need help with?

It is java script i believe since i do it in html with the <script> tag. He didn't write anything else but i believe he means i need to take each numeric grade and [ex. 90-93] and it needs to return the letter grade[A in this case].
 

Tuck

Member
I took programming in high school - we learned Python. I really enjoyed it, and I'd like to start programming again, as a hobby.

I'm just confused as to what language I should attempt to learn. I forget most of Python, but I'm pretty sure I would start to remember a lot of it once I start playing around with it. So in that sense, it might be the easiest for me to learn. But I'm not sure if its the right language to learn. Long term, I'd like to maybe make a small game or make an OSX application, or an iPhone/android app. Not exactly specific, but it would be one of those things. Short term, I just want to enjoy learning to program.

So... advice? C? Or do I jump right into Objective C or C++? Or maybe stick with Python? Too many options...

EDIT: I did try Googling this to see if there were any articles on it, but I'm still a little lost in deciding.
 
It is java script i believe since i do it in html with the <script> tag. He didn't write anything else but i believe he means i need to take each numeric grade and [ex. 90-93] and it needs to return the letter grade[A in this case].

http://www.w3schools.com/js/js_switch.asp

So... advice? C? Or do I jump right into Objective C or C++? Or maybe stick with Python? Too many options...

For learning? I would go with C++. You will wrap your head around OO and will still be able to do cool stuff like make games with CryEngine and all sorts of things (reality is you will never really be coding games from scratch). Even for your ios/android goal, you are better off taking something like Unity or where you will just be mostly scripting.

Once you are really comfortable with how to program nicely, you can then throw it all out the window and jump into Objective C if you really feel the need.
 
I don't actually think that's what he would want to use since he's looking at ranges of values.

A series of if / else if statements will do.

Basically:

Code:
if ( grade < 70 ) {
  return 'F';
}
else if ( grade < 76 ) {
  return 'C';
}
else if ( grade < 81 ) {
  return 'C+';
}
...

yea i was trying something similar to this but for some reason it doesn't work. it says grade is not defined.
 
Top Bottom