Skip to main content

Help assigning value to byte data type...

1 reply [Last post]
jeffbroodwar
Offline
Joined: 2006-11-27
Points: 0

Hello, i have a problem about assigning a char value to a byte... please check the code below :

========================================================
Scenario # 1 : This code doesn't work :

byte[] buffer = new byte[256];
char tempValue;
int StartAddress;

buffer[StartAddress] = tempValue;

ERROR : possible loss of precision
explanation : if i try to save a char variables value to byte,i get the error message above....

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

========================================================
Scenario # 2 : This code doesn't work :

byte[] buffer = new byte[256];
int StartAddress;

buffer[StartAddress] = '10';

ERROR : unclosed character literal bla bla bla bla
explanation : if i try to save a char value composed of 2 characters to byte,i get the error message above....

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

========================================================
Scenario # 3 : This code works :

byte[] buffer = new byte[256];
int StartAddress;

buffer[StartAddress] = '2';

explanation : if i try to save a char value composed of 1 character to byte,i dont get any error. but the problem is i need to make Scenario # 1 work. what i need is to save the content of character Ex: charVariable = Microsoft to this array of bytes using charAt........ i cant make it work using charAt... it seems that it's looking for the ' ' symbols before and after the character values..... please help. thanks in advance..
=========================================================

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
neunerball
Offline
Joined: 2005-11-22
Points: 0

This should work for Scenario #1

byte[] buffer = null;
char tempValue = '2';

buffer = String.valueOf(tempValue).getBytes();

the last line is a combination first the tempValue is converted to a string, then using the getBytes() method of the String class to convert to a byte[] of length 1.

If you are trying to convert a string variable into a byte[] it works like this:

String someString = "SomeValue";
byte[] buffer = someString.getBytes();