# Problem with type conversion and color

**URL:** https://discourse.processing.org/t/problem-with-type-conversion-and-color/45570
**Category:** Beginners
**Created:** [January 10, 2025, 12:20pm UTC](https://discourse.processing.org/t/problem-with-type-conversion-and-color/45570 "2025-01-10T12:20:23Z")
**Posts on this page:** 14
**Page:** 1

<div class="post-metadata">

### Author: ![paulstgeorge](https://avatars.discourse-cdn.com/v4/letter/p/53a042/32.png) [@paulstgeorge](https://discourse.processing.org/u/paulstgeorge)
#### Post date: [January 10, 2025, 12:20pm UTC](https://discourse.processing.org/t/problem-with-type-conversion-and-color/45570/1 "2025-01-10T12:20:23Z")

</div>

I have an integer j. I convert it to a character k, with value b. Then I want to fill a rectangle with color b by calling ` fill(k)`;

It (see below) does not work. Can anyone please tell me why?

```auto
char k;
color b = color(237.0, 116.0, 75.0); //45

void setup() {
  size(400, 400);

  noLoop();
}

void draw() {
  background(112);

  noStroke();

  //color
  int j = 98;
  k = char(j);
  //println(k);

  //fill(b);
  fill(k);
  rect(0, 0, 400, 400);
}

```

---

<div class="post-metadata">

### Author: ![eightohnine](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/eightohnine/32/19793_2.png) [@eightohnine](https://discourse.processing.org/u/eightohnine)
#### Post date: [January 11, 2025, 9:22am UTC](https://discourse.processing.org/t/problem-with-type-conversion-and-color/45570/2 "2025-01-11T09:22:42Z")

</div>

`fill(k);` takes the character ‘b’ but uses its numerical representation, which is 98. So it’s `fill(98);` which creates a dark grey fill. _Technically_ the sketch is running as expected.

I’m intrigued by what you expected to happen. My _assumption_ is that you imagine that character ‘b’ to act as a reference to your color variable `b` and that the rect would have an orangey fill?

I’m double-assuming that you eventually want to load in a String and then have each individual character generate a specific color? That’s definitely possible, but would require a different approach.

– – –

No matter if I I’m right or totally off about the goal of your sketch, I’ll use this opportunity to plug one of my all-time favourite generative Text-to-Visual projects. It’s the [Poetry](https://www.esono.com/boris/projects/poetry02/) [on](https://www.esono.com/boris/projects/poetry06/) [the](https://www.esono.com/boris/projects/poetry11/) [Road](https://www.esono.com/boris/projects/poetry03/) series of posters by Boris Müller and they are excellent.

---

<div class="post-metadata">

### Author: ![paulstgeorge](https://avatars.discourse-cdn.com/v4/letter/p/53a042/32.png) [@paulstgeorge](https://discourse.processing.org/u/paulstgeorge)
#### Post date: [January 11, 2025, 9:54am UTC](https://discourse.processing.org/t/problem-with-type-conversion-and-color/45570/3 "2025-01-11T09:54:02Z")

</div>

Yes, I want the fill to be color(b) so in my dreams `fill(k)` would have same result as `fill(b)`.  
My ultimate aim is to iterate through a number of colors. I can easily iterate through integers so I thought I would change the integer to a letter and then refer to the color.  
I can do what I want with an array of colors and then the integer is an index number representing a position in the array. That works fine, but I didn’t want to give up on the type-conversion approach (yet). Is there any hope?

Will investigate Boris Müller, thank you.

---

<div class="post-metadata">

### Author: ![quark](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/quark/32/26_2.png) [@quark](https://discourse.processing.org/u/quark)
#### Post date: [January 11, 2025, 10:18am UTC](https://discourse.processing.org/t/problem-with-type-conversion-and-color/45570/4 "2025-01-11T10:18:34Z")

</div>

**As @GoToLoop kindly pointed out my original post here was incorrect. I have edited this post since I don’t want readers to be misinformed. This post now correctly represents the situation as it applies to the Java language.**

======================================================================

> [@paulstgeorge](#):
>
> `color b = color(237.0, 116.0, 75.0); //45`

in this statement the first part `color b` declares a variable called `b` of data type `color` but Processing will convert this to `int b`.

In Processing colors are represent by 4 bytes representing the 4 channels ARGB (alpha, red, green, blue) and are collectively stored as an integer.

A `char` is represented by 2 bytes that are used to store Unicode characters. Characters with Unicode values in the range `0` to `255` represent the Extended ASCII set of which the values `0` to `127` represent the standard ASCII set.

Try the following code it should give an insight into what is happening -

```auto
color a = color(237.0, 116.0, 75.0);
char ch = (char)a; // cast int value to char
int s = (int)ch; // cast char value to short
byte b = (byte)ch; // cast char value to byte

// OUTPUT
println("Color value of a = " + a); // -1215413
println("Printable value of ch = '" + ch + "'"); // 瑋
println("Numeric value of ch = " + s); // 29771
println("Byte value of ch c = " + b); // 75

```

In the statement `char c = char(b);` we are casting an integer to a short. Using a bit representation we are doing -

```auto
AAAAAAAARRRRRRRRGGGGGGGGBBBBBBBB // 32 bit int representing a color ARGB
                 GGGGGGGGBBBBBBB // after casting to a short
                         BBBBBBB // after casting to a byte

```

This shows that a short or char cannot hold a full ARGB color value.

---

<div class="post-metadata">

### Author: ![paulstgeorge](https://avatars.discourse-cdn.com/v4/letter/p/53a042/32.png) [@paulstgeorge](https://discourse.processing.org/u/paulstgeorge)
#### Post date: [January 11, 2025, 12:53pm UTC](https://discourse.processing.org/t/problem-with-type-conversion-and-color/45570/5 "2025-01-11T12:53:08Z")

</div>

OK. Very clear, thank you!  
Is the following the best (only?) way to iterate through colors?

```auto
color[] colors = {
  color(236.0, 112.0, 83.0),
  color(237.0, 116.0, 75.0),
  color(236.0, 121.0, 67.0),
  color(236.0, 127.0, 60.0),
  color(230.0, 102.0, 105.0)
};

void setup() {
  size(400, 400);

  noLoop();
}

void draw() {
  for (int i = 0; i < colors.length; i++) {

    fill(colors[i]);

    rect(0, 0, 400, 400);

    saveFrame("data/"+i+".tif");
  }
}

```

---

<div class="post-metadata">

### Author: ![Chrisir](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/chrisir/32/45_2.png) [@Chrisir](https://discourse.processing.org/u/Chrisir)
#### Post date: [January 11, 2025, 1:03pm UTC](https://discourse.processing.org/t/problem-with-type-conversion-and-color/45570/6 "2025-01-11T13:03:56Z")

</div>

maybe `lerpColor` is interesting

see reference [lerpColor() / Reference / Processing.org](https://processing.org/reference/lerpColor_.html)

* * *

**Example**

```auto
// Demo for lerpColor

size(1100, 180);

color from = color(204, 102, 0);
color to = color(0, 102, 153);

for (int i=0; i <= 255; i=i+1) {
  // println(i);
  float amt = map( i, 0, 255, 0, 1 );
  color c = lerpColor (from, to, amt);
  fill(c);
  noStroke();
  rect(i*4, 0, 4, 12);
}// End for-loop

println("");
println("End.");

```

---

<div class="post-metadata">

### Author: ![glv](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/glv/32/18785_2.png) [@glv](https://discourse.processing.org/u/glv)
#### Post date: [January 11, 2025, 1:19pm UTC](https://discourse.processing.org/t/problem-with-type-conversion-and-color/45570/7 "2025-01-11T13:19:14Z")

</div>

> [@paulstgeorge](#):
>
> Is the following the best (only?) way to iterate through colors?

Some resources here:

> [@HSB resolution Question](https://discourse.processing.org/t/hsb-resolution-question/29735/4):
>
> Hello, Some references on Processing website: [Color \ Processing.org](https://processing.org/tutorials/color/)[color() \ Language (API) \ Processing 3+](https://www.processing.org/reference/color_.html)[colorMode() \ Language (API) \ Processing 3+](https://processing.org/reference/colorMode_.html) Many others in references On Medium: [Color Gradients in Processing (v 2.0) | by Jeremy Behreandt | Medium](https://behreajj.medium.com/color-gradients-in-processing-v-2-0-e5c0b87cdfd2) Examples on Processing website and in Processing PDE: [image] The Processing PDE has a Color Selector in the Tools menu: [image] slight_smile

I have a lot of fun with gradients!

> [@HSB Color Gradient](https://discourse.processing.org/t/hsb-color-gradient/29795):
>
> HSB color gradient sweeping through hue with 100% saturation and 100% brightness. I have done similar with loops for RGB colorMode() and this is the same outcome (close) with HSB colorMode. I wanted to use integers and sweep through all the possible combinations at 100% sat and 100% brightness in integer steps as part of this exploration. // HSB Gradient Exploration // v1.0.0 // GLV 2021-05-01 int hue = 1536; //256\*6 hue combinations; actually 3x triplets are identical so 256\*6 - 6! int coun…

`:)`

---

<div class="post-metadata">

### Author: ![paulstgeorge](https://avatars.discourse-cdn.com/v4/letter/p/53a042/32.png) [@paulstgeorge](https://discourse.processing.org/u/paulstgeorge)
#### Post date: [January 11, 2025, 4:00pm UTC](https://discourse.processing.org/t/problem-with-type-conversion-and-color/45570/8 "2025-01-11T16:00:40Z")

</div>

They are great resources, thank you. The closest to my project is your HSB Gradient Exploration.

The thing is, I am starting from Hues, then manipulating other values so, for example, the Luminosity and Chromaticity. Then after many lines of code, I want to save sample swatches. I wanted to go from beginning to end without saving the colours in an array.

So

iterate \> modify some dimensions (not linear) \> save swatches

rather than

iterate \> modify some dimensions (not linear) \> append to an array \> save swatches

I’ll look through the examples you have shared to see if there is an alternative to the array approach. And thank you again.

---

<div class="post-metadata">

### Author: ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)
#### Post date: [January 11, 2025, 4:44pm UTC](https://discourse.processing.org/t/problem-with-type-conversion-and-color/45570/9 "2025-01-11T16:44:16Z")

</div>

> [@quark](#):
>
> A `char` is a single byte that can store a value in the range 0-255 inclusive.

> [@quark](#):
>
> In the statement `char c = char(b);` we are casting an integer to a byte.

That is so in languages such as C and C++, but not in Java!

Java’s primitive datatype `char` is the same as `short` in its storage of 16 bits (2 bytes); but it’s the only `unsigned` type among the 8 primitive types, ranging from 0 to 65535:

> **[char / Reference](https://processing.org/reference/char.html)**
>
> Datatype for characters, typographic symbols such as A, d, and $. A char stores letters and symbols in the Unicode format, a coding system developed to support a variety of world languages. Eac…

The `char` type is mostly used to represent a 16-bit UNICODE (UTF16) character in Java.

Primitive datatype `char` has other special behaviors such as when we print its value, logging the corresponding ASCII/UNICODE character instead of its actual numerical value.

Also when it’s used on a concatenation expression, behaving as a string rather than a number.

---

<div class="post-metadata">

### Author: ![quark](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/quark/32/26_2.png) [@quark](https://discourse.processing.org/u/quark)
#### Post date: [January 11, 2025, 6:07pm UTC](https://discourse.processing.org/t/problem-with-type-conversion-and-color/45570/10 "2025-01-11T18:07:56Z")

</div>

@GoToLoop thanks for the correction.

In all my years of Java programming I have very, very rarely had the need to use the Java `char` and `short` data types. Thinking about it I rarely used them in C++ either. 😌

EDIT: I have corrected my previous post 👍

---

<div class="post-metadata">

### Author: ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)
#### Post date: [January 12, 2025, 1:11pm UTC](https://discourse.processing.org/t/problem-with-type-conversion-and-color/45570/11 "2025-01-12T13:11:40Z")

</div>

> [@quark](#):
>
> EDIT: I have corrected my previous post 👍

There’s still a small oversight over the actual range of `char`, which isn’t the same as `short`!  
`char` is the only unsigned primitive type in Java; so its range is `0` to `65535` instead:

> [@quark](#):
>
> A `char` is represented by 2 bytes (`short` data type) that can store a value in the range `-32768` to `32767` inclusive

---

<div class="post-metadata">

### Author: ![glv](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/glv/32/18785_2.png) [@glv](https://discourse.processing.org/u/glv)
#### Post date: [January 12, 2025, 2:13pm UTC](https://discourse.processing.org/t/problem-with-type-conversion-and-color/45570/12 "2025-01-12T14:13:59Z")

</div>

> [@GoToLoop](#):
>
> `char` is the only unsigned primitive type in Java; so its range is `0` to `65535`

Adding some references to topic:  
[Primitive Data Types (The Java™ Tutorials \> Learning the Java Language \> Language Basics)](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html) \< The true source!

[Unsigned short in Java | Programming.Guide](https://programming.guide/java/unsigned-short.html) \< Interesting!

I find that some sites do not list the `char` description the same as the Oracle website.

`:)`

---

<div class="post-metadata">

### Author: ![quark](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/quark/32/26_2.png) [@quark](https://discourse.processing.org/u/quark)
#### Post date: [January 12, 2025, 3:17pm UTC](https://discourse.processing.org/t/problem-with-type-conversion-and-color/45570/13 "2025-01-12T15:17:41Z")

</div>

@GoToLoop thanks again for the new correction I have removed all references to the `short` data type as it didn’t add anything to this topic.

Messing about with my code above reminded me why I never bothered to use the `short` data type as doing any form of mathematics seems to be a nightmare. As for `char` it’s only use I have found for it is to check keyboard events and that extremely rarely. 😀

---

<div class="post-metadata">

### Author: ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)
#### Post date: [January 12, 2025, 4:18pm UTC](https://discourse.processing.org/t/problem-with-type-conversion-and-color/45570/14 "2025-01-12T16:18:45Z")

</div>

> [@quark](#):
>
> … why I never bothered to use the `short` data type as doing any form of mathematics seems to be a nightmare.

Storing in arrays or other containers smaller datatypes such as `boolean`, `byte`, `short`, `char` and `float` can lead to significant performance gain due to the way our modern CPUs transfer contiguous memory blocks to their cache “pipelines”.

BtW, I’ve asked Bing AI about it for more details:

> Certainly! Let’s delve into how using different primitive types in arrays can impact CPU pipelines and performance:
> 
> ### **CPU Pipelines and Data Sizes**
> 
> 1. **Instruction Pipelining** : Modern CPUs use instruction pipelines to execute multiple instructions concurrently. Efficient use of the pipeline can be influenced by the size of the data being processed. Smaller data types like `short`, `char`, and `float` can help improve this efficiency.
> 
> 2. **Memory Bandwidth** : Smaller data types use less memory bandwidth, meaning that more data can be loaded into the cache or registers at once. This reduces the number of memory accesses required, leading to faster processing.
> 
> 3. **Cache Utilization** : Smaller data types can better utilize the CPU cache. For example, using `short` (2 bytes) instead of `int` (4 bytes) means that twice as many elements can fit into the same cache line. This reduces cache misses and increases the likelihood that the required data is already available in the cache.
> 
> ### **Short/Char vs. Int Arrays**
> 
> 1. **Memory Savings** : `short` and `char` are 2 bytes each, whereas `int` is 4 bytes. When using `short` or `char` arrays, you effectively halve the memory footprint compared to `int` arrays.
> 2. **Alignment and Padding** : Smaller data types can lead to better memory alignment, reducing padding and improving memory access patterns. This can result in more efficient use of the CPU pipeline.
> 
> ### **Float Arrays vs. Double Arrays**
> 
> 1. **Memory Usage** : `float` is 4 bytes, while `double` is 8 bytes. Using `float` arrays instead of `double` arrays can result in significant memory savings.
> 2. **Precision Considerations** : While `float` provides less precision than `double`, it is sufficient for many applications. The reduced precision can lead to faster computations due to the lower memory overhead.
> 
> ### **Trade-offs**
> 
> - **Precision** : Using smaller data types like `float` instead of `double` may lead to loss of precision, which can be critical in certain applications such as scientific computations.
> - **Overflow/Underflow** : Smaller data types have lower range limits, increasing the risk of overflow or underflow in calculations.
> - **Platform-Specific Optimizations** : Some CPUs might have specific optimizations for certain data types. For example, some processors have more efficient floating-point units for `double` precision than for `float`.
> 
> In summary, using smaller primitive data types can lead to better CPU pipeline efficiency, improved cache utilization, and overall performance gains, especially in memory-constrained applications. However, it’s important to balance these benefits with potential trade-offs in precision and range.
